spring 經過spring-data-redis 整合redis ,經過 RedisTemplate 類進行內存上的管理redis
覺得爲系統根據自身的需求對redis緩存進行包裝處理 spring
代碼 :緩存
public class RedisCacheManager implements CacheManager {ide
private Logger log = Logger.getLogger(this.getClass());this
@Resource(name = "redisTemplate")
private RedisTemplate<String, Object> redisTemplate;.net
@Override
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);
}
}get
@Override
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;
}
}it
@Override
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;
}
}io
@Override
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; } } }