forked from tanglijiong/MyJavaStudio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyCache.java
More file actions
110 lines (90 loc) · 2.37 KB
/
Copy pathMyCache.java
File metadata and controls
110 lines (90 loc) · 2.37 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package com.xjj.cache.local;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyCache {
static public Logger logger = LoggerFactory.getLogger(MyCache.class);
/**
* 存放规则:{key, CacheObject(value, expireDt)}
* e.g. {class_code, CacheObject(Map{code, name}, expireDt)}
*/
private Map<String, CacheObject> cache;
private int auditIntervalInSeconds = 20;
public MyCache() {
cache = new ConcurrentHashMap<String, CacheObject>();
Timer taskTimer = new Timer(true);
taskTimer.scheduleAtFixedRate(new LocalCacheAuditor(), 1000*3, auditIntervalInSeconds*1000);
logger.info("Local cache instance and auditor created.");
}
/**
* key是否存在
* @author XuJijun
* @param key
* @return
*/
public boolean keyExists(String key) {
if (key == null || "".equals(key)) {
logger.error("The key [{}] is empty.", key);
return false;
}
return cache.containsKey(key);
}
public boolean put(String key, Object value) {
if(key == null || "".equals(key)){
return false;
}
CacheObject cacheObject = new CacheObject(value);
cache.put(key, cacheObject);
return true;
}
public boolean put(String key, Object value, long ageInSeconds) {
if(key == null || "".equals(key)){
return false;
}
CacheObject cacheObject = new CacheObject(value, ageInSeconds);
cache.put(key, cacheObject);
return true;
}
public CacheObject get(String key) {
if(key == null || "".equals(key)){
return null;
}
CacheObject co = cache.get(key);
if(co==null){
return null;
}
if(co.isAvailable()){
return co;
}else{
//已经过期
logger.debug("Remove expired data [{}] from local cache.", key);
cache.remove(key);
return null;
}
}
@Override
public String toString() {
return "LocalCache [cacheDataMap=" + cache + "]";
}
/**
* 清理过期的cacheObject
* @author Xu
*
*/
class LocalCacheAuditor extends TimerTask {
public void run() {
logger.info("Clear the expired data from local cache...");
Set<String> keySet = cache.keySet();
for (String key : keySet) {
if(!cache.get(key).isAvailable()) {
cache.remove(key);
logger.info("Local Cache Auditor: remove expired data [{}] from local cache.", key);
}
}
}
}
}