CacheKeyHelper.java
2.27 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
83
84
85
package com.yoho.unions.helper;
import com.alibaba.fastjson.JSON;
import com.netflix.config.DynamicBooleanProperty;
import com.netflix.config.DynamicPropertyFactory;
import com.yoho.unions.common.enums.CacheKeyEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 缓存所有的KEY的管理 格式: 所有的KEY均由 yh:users:XXXX 开头
*
* @author Created by dengxinfei on 2016/3/13.
*/
public class CacheKeyHelper {
static Logger log = LoggerFactory.getLogger(CacheKeyHelper.class);
/**
* 根据枚举,获取该枚举对应的缓存key
* 获取之前需要判断缓存总开关和该缓存对应的开关
* 开关配置在cachesSwitch.properties中
* @param cacheKey
* @param obj
* @return
*/
public static String getCacheKeyAndCheck(CacheKeyEnum cacheKey, Object obj) {
//获取总开关
DynamicBooleanProperty totalOnoff = DynamicPropertyFactory.getInstance().getBooleanProperty("redis.total.key.switch", false);
log.info("getCacheKeyAndCheck. totalOnoff is {}, cacheKey is {}, obj is {}", totalOnoff.get(), cacheKey, obj);
if (!totalOnoff.get()) {
return null;
}
//如果开关的key为空,则用缓存key代替
String switchKey = cacheKey.getSwitchKey();
if (StringUtils.isEmpty(switchKey)) {
switchKey = cacheKey.getCacheKey();
}
//获取该缓存对应的开关
DynamicBooleanProperty onoff = DynamicPropertyFactory.getInstance().getBooleanProperty(switchKey, false);
if (!onoff.get()) {
return null;
}
log.debug("getCacheKeyAndCheck key is {}", cacheKey.getCacheKey());
return cacheKey.getCacheKey() + obj;
}
/**
* 序列化value值
* @param value
* @return
*/
public static <T> String value2String(T value) {
String v = null;
if (value == null) {
return null;
}
if (value instanceof String) {
v = (String) value;
} else {
v = JSON.toJSONString(value);
}
return v;
}
/**
* 反序列化value值
* @param value
* @param clazz
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T string2Value(String value, Class<T> clazz) {
if (StringUtils.isEmpty(value)) {
return null;
}
if (clazz.getName().equalsIgnoreCase("java.lang.String")) {
return (T) value;
}
return (T) JSON.parseObject(value, clazz);
}
}