SSM项目集成Redis
阅读原文时间:2023年07月08日阅读:1

1. 加入依赖


redis.clients jedis 2.9.0

org.springframework.data spring-data-redis 2.1.0.RELEASE

2. 配置文件redis-context.xml


http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">







redis.properties

redis.host=192.168.181.130
redis.port=6379
redis.maxIdle=300
redis.maxWaitMillis=1000
redis.maxTotal=600
redis.testOnBorrow=true
redis.testOnReturn=true

在 Spring 的配置文件中引入 redis 的 xml 文件

3. 测试

service:

@Service
public class RedisServiceImpl implements RedisService {

@Autowired  
private StringRedisTemplate redisTemplate;

/\*  
\* 将字符串类型的键值对保存到Redis时调用  
\* \*/  
@Override  
public Boolean saveNormalStringKeyValue(String normalKey, String normalValue, Integer timeoutMinute) {  
    // 获取字符串操作器对象  
    ValueOperations<String, String> operator = redisTemplate.opsForValue();  
    // 判断timeoutMinute值:是否为无效值  
    if(timeoutMinute == null || timeoutMinute == 0) {  
        return false;  
    }  
    // 判断timeoutMinute值:是否为不设置过期时间  
    if(timeoutMinute == -1) {  
        // 按照不设置过期时间的方式执行保存  
        try {  
            operator.set(normalKey, normalValue);  
        } catch (Exception e) {  
            e.printStackTrace();  
            return false;  
        }  
        // 返回结果  
        return true;  
    }  
    // 按照设置过期时间的方式执行保存  
    try {  
        operator.set(normalKey, normalValue, timeoutMinute, TimeUnit.MINUTES);  
    } catch (Exception e) {  
        e.printStackTrace();  
        return false;  
    }  
    return true;  
}

/\*\*  
 \* 根据key查询对应value时调用  
 \*/  
@Override  
public String retrieveStringValueByStringKey(String normalKey) {

    try {  
        String value = redisTemplate.opsForValue().get(normalKey);

        return value;

    } catch (Exception e) {  
        e.printStackTrace();

        return "";  
    }  
}

/\*\*  
 \* 根据key删除对应value时调用  
 \*/  
@Override  
public Boolean removeByKey(String key) {

    try {  
        redisTemplate.delete(key);

        return true;

    } catch (Exception e) {  
        e.printStackTrace();

        return false;  
    }  
}  

}

在 controller 中调用 service :

redisservice.xxx();