spring 通过spring-data-redis 整合redis ,通过 RedisTemplate 类进行内存上的管理
以为为系统根据自身的需求对redis缓存进行包装处理
代码 :
public class RedisCacheManager implements CacheManager {
private Logger log = Logger.getLogger(this.getClass());
@Resource(name = "redisTemplate")
private RedisTemplate<String, Object> redisTemplate;public void put(String key, Object value, int timeToLive) { if (key == null || value == null) { return; }
try {
if (timeToLive > 0) { redisTemplate.opsForValue().set(key, value, timeToLive, TimeUnit.SECONDS); } else { redisTemplate.opsForValue().set(key, value); } } catch (Exception e) { log.error(e.getMessage(), e); } }public boolean add(String key, Object value, int timeToLive) { if (key == null || value == null) { return false; } try { boolean success = redisTemplate.opsForValue().setIfAbsent(key, value); if (success && timeToLive > 0) { redisTemplate.expire(key, timeToLive, TimeUnit.SECONDS); } return success; } catch (Exception e) { log.error(e.getMessage(), e); return false; } }
public Object get(String key) { if (key == null) { return null; } try { return redisTemplate.opsForValue().get(key); } catch (Exception e) { log.error(e.getMessage(), e); return null; } }
public Object getAndTouch(String key, int timeToLive) { if (key == null) return null; Object rs = redisTemplate.opsForValue().get(key); if(rs != null && timeToLive > 0){ redisTemplate.expire(key, timeToLive, TimeUnit.SECONDS); } return rs; }
@Override
public void delete(String key) { if (key == null) { return; }try {
redisTemplate.delete(key); } catch (Exception e) { log.error(e.getMessage(), e); } }@Override
public boolean containsKey(String key) { if (key == null){ return false; } try { return redisTemplate.hasKey(key); } catch (Exception e) { log.error(e.getMessage(), e); return false; } } }