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
package com.tanpu.community.cache;
import com.tanpu.common.exception.BizException;
import com.tanpu.common.util.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.function.Supplier;
@Service
public class LocalCache {
@Autowired
private CaffeineCacheManager cacheManager;
private Cache localCache;
@PostConstruct
public void init() {
localCache = cacheManager.getCache("local");
if (localCache == null) {
throw new BizException("local cache not found!");
}
}
public <T> T getObject(String key, Class<T> clz) {
return localCache.get(key, clz);
}
public <T> void putObject(String key, T value) {
localCache.put(key, value);
}
public<T> T getObject(String key, Supplier<T> func, Class<T> clz) {
T value = localCache.get(key, clz);
if (value != null) {
return value;
}
T ret = func.get();
if (ret != null) {
localCache.put(key, ret);
}
return ret;
}
}