RedisValueCache.java
2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.yohoufo.user.cache;
import com.yoho.core.redis.cluster.annotation.Redis;
import com.yoho.core.redis.cluster.operations.nosync.YHRedisTemplate;
import com.yoho.core.redis.cluster.operations.nosync.YHValueOperations;
import com.yoho.core.redis.cluster.operations.serializer.RedisKeyBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
* Created by zhouxiang on 2016/5/31.
*/
@Component
public class RedisValueCache {
private final static Logger logger = LoggerFactory.getLogger(RedisValueCache.class);
@Redis("yohoNoSyncRedis")
YHRedisTemplate yHRedisTemplate;
@Redis("yohoNoSyncRedis")
YHValueOperations yhValueOperations;
public Long incrementWithExpire(RedisKeyBuilder cacheKey, long delta , long timeout, TimeUnit unit) {
logger.debug("Enter increment valueOperation redis.key is {},delta is {}", cacheKey, delta);
try {
Long num = yhValueOperations.increment(cacheKey, delta);
yHRedisTemplate.longExpire(cacheKey, timeout, unit);
return num;
} catch (Exception e) {
try{
yHRedisTemplate.longExpire(cacheKey, timeout, unit);
}catch (Exception e1){
logger.error("RedisValueHelper expire redis again error. with key={}", cacheKey, e1);
}
logger.warn("Redis exception. increment fail,key {},delta is {}, error msg is {}", cacheKey, delta, e);
}
return 0L;
}
/**
* 设置值
*
* @param cacheKey
* @param value
* @param timeout
* @param unit
* @param <T>
*/
public <T> void set(RedisKeyBuilder cacheKey, T value, long timeout, TimeUnit unit) {
logger.debug("Enter set valueOperation redis value.key is {},value is {}", cacheKey, value);
try {
String v = CacheHelper.value2String(value);
yhValueOperations.set(cacheKey, v, timeout, unit);
} catch (Exception e) {
logger.warn("Redis exception. value redis set,key {},value is {}, error msg is {}", cacheKey, value, e);
}
}
/**
* 取值
*
* @param cacheKey
* @param clazz
*/
public <T> T get(RedisKeyBuilder cacheKey, Class<T> clazz) {
logger.debug("Enter get valueOperation redis value.key is {}", cacheKey);
try {
String value = yhValueOperations.get(cacheKey);
return CacheHelper.string2Value(value, clazz);
} catch (Exception e) {
logger.warn("Redis exception. value redis get,key {}, error msg is {}", cacheKey, e);
}
return null;
}
}