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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package com.yanzuoguang.util.cache;
import com.yanzuoguang.util.YzgError;
import com.yanzuoguang.util.exception.CodeException;
import com.yanzuoguang.util.helper.StringHelper;
/**
* 服务工具类
*
* @author 颜佐光
*/
public abstract class MemoryCacheNullUtil<T, M> {
/**
* 缓存的公司和数据中心Id
* 缓存一个小时
*/
private final MemoryCache<M> cache = new MemoryCache<>(60 * 60);
/**
* 缓存的公司和数据中心Id
* 缓存一分钟
*/
private final MemoryCache<Boolean> cacheIsNull = new MemoryCache<>(60);
public MemoryCacheNullUtil() {
}
/**
* 缓存参数
*
* @param cacheSecond
* @param nullSecond
*/
public MemoryCacheNullUtil(int cacheSecond, int nullSecond) {
cache.setClearSecond(cacheSecond);
cacheIsNull.setClearSecond(nullSecond);
}
/**
* 获取数据中心Id
*
* @param key
* @return
*/
public M getCheck(T key) {
M databaseId = get(key);
if (databaseId == null) {
throw YzgError.getRuntimeException("049", key);
}
return databaseId;
}
/**
* 获取数据中心Id
*
* @param key
* @return
*/
public M get(T key) {
String keyString = getKey(key);
M value = cache.get(keyString);
if (value == null) {
if (StringHelper.toBoolean(cacheIsNull.get(keyString))) {
return null;
}
value = getValue(key);
setCache(keyString, value);
}
return value;
}
/**
* 获取关键字
*
* @param key
* @return
*/
protected abstract String getKey(T key);
/**
* 获取数据
*
* @param key
* @return
*/
protected abstract M getValue(T key);
/**
* 写入缓存
*
* @param key
* @param value
*/
protected void setCache(String key, M value) {
cacheIsNull.remove(key);
cache.remove(key);
if (value == null) {
cacheIsNull.put(key, true);
} else {
cache.put(key, value);
}
}
}