Repository navigation
Expand file tree
/
Copy pathLocalCache.java
More file actions
89 lines (73 loc) · 2.52 KB
/
Copy pathLocalCache.java
File metadata and controls
89 lines (73 loc) · 2.52 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
package guava;
import com.google.common.cache.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;
public class LocalCache {
private static LoadingCache<String, List<String>> caches;
public static void main(String[] args) throws Exception {
initCache();
for (int i = 0; i< 10; i++) {
getValue("1");
Thread.sleep(200);
}
Thread.sleep(10000);
}
public static void initCache() {
CacheLoader<String, List<String>> loader = initCacheLoader();
RemovalListener<String, List<String>> removalListener = new RemovalListener<String, List<String>>() {
@Override
public void onRemoval(RemovalNotification<String, List<String>> removal) {
System.out.println("remove cache key:" + removal.getKey());
}
};
caches = CacheBuilder.newBuilder()
.maximumSize(100)
.expireAfterAccess(1, TimeUnit.SECONDS)
.expireAfterWrite(1, TimeUnit.SECONDS)
// key remove listener
.removalListener(removalListener)
.build(loader);
}
private static CacheLoader initCacheLoader() {
CacheLoader<String, List<String>> loader = new CacheLoader<String, List<String>>() {
@Override
public List<String> load(String key) {
return remoteLoadData(key);
}
};
CacheLoader.asyncReloading(loader, Executors.newSingleThreadExecutor());
return loader;
}
private static List<String> getValue(String key) {
long start = System.currentTimeMillis();
List<String> list = null;
try {
list = caches.get(key);
} catch (ExecutionException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println(String.format("get key=%s, cost=%s ms ", key, end-start));
return list;
}
/**
*
* @param key
* @return
*/
private static List<String> remoteLoadData(String key) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add(key + "_" + String.valueOf(new Date().getTime()));
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(String.format("the key=%s get data from remote", key));
return list;
}
}