service层:
public interface RedisService {
//把字符串类型的value写入缓存
public boolean setString(String key,String value);
//把字符串类型的value写入缓存(有失效时间)
public boolean setString(String key ,String value, long time);
//将value以json格式写入缓存()
public boolean setObject(String key,Object value ,long time);
//获取缓存String
public String getString(String key);
//获取缓存json对象
public <T> T getObj(String key,Class<T> clazz);
//删除缓存
public boolean del(String key);
}
//实现类:
public class RedisServiceImpl implemenets RedisService {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate<String, ?> redisTemplate;
@Value("${项目名.system-id}")
private String redisPrefix;
//设置带项目前缀的key值,防止key重复
private String buildRedisKey(String key) {
retrun redisPrefix +key;
}
public boolean setString(String key,String value, long time){
stringRedisTemplate.opsForValue().set(buildRedisKey(key), value);
if(time >0){
stringRedisTemplate.expire(buildRedisKey(key), time ,TimeUnit.SECONDS);
}
return true;
}
public boolean setString(String key ,String value){
return setString(key ,value , 0);
}
public boolean setObj(String key, Object value, long time){
stringRedisTemplate.opsForValue().set(buildRedisKey(key) ,JSON.toJSONString(value));
if(time >0){
stringRedisTemplate.expire(buildRedisKey(key), time ,TimeUnit.SECONDS);
}
return true;
}
public String getString(String key){
return stringRedisTemplate.boundValueOps(buildRedisKey(key)).get();
}
public <T> T getObj(String key ,Class<T> clazz){
String s =stringRedisTemplate.boundValueOps(buildRedisKey(key)).get();
return JSON.parseObject(s ,clazz);
}
public boolean del(String key){
redisTemplate.delete(buildRedisKey(key));
return true;
}
}
}