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
package com.tanpu.community.cache;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.tanpu.common.redis.RedisHelper;
import com.tanpu.common.redis.RedisKeyHelper;
import com.tanpu.common.util.JsonUtil;
import com.tanpu.community.util.SpringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.List;
import java.util.function.Supplier;
public class RedisCache {
private String cacheName;
private RedisHelper redisHelper;
public<T> T getObject(String key, Integer expireSeconds, Supplier<T> func, Class<T> clz) {
String value = get(key);
// todo 考虑缓存穿透的问题.
if (StringUtils.isNotBlank(value)) {
return JsonUtil.toBean(value, clz);
}
T ret = func.get();
if (ret != null) {
put(key, ret, expireSeconds);
}
return ret;
}
public<T> T getList(String key, Integer expireSeconds, Supplier<T> func, TypeReference<T> ref) {
String value = get(key);
if (StringUtils.isNotBlank(value)) {
return JsonUtil.toBean(value, ref);
}
T ret = func.get();
if (ret != null) {
put(key, ret, expireSeconds);
}
return ret;
}
public void evict(String key) {
delete(key);
}
private String get(String key) {
key = cacheName + ":" + key;
return redisHelper.get(key);
}
private void put(String key, Object obj, Integer expireSeconds) {
key = cacheName + ":" + key;
String value = JsonUtil.toJson(obj);
if (expireSeconds == 0) {
redisHelper.set(key, value);
} else {
redisHelper.set(key, value, Duration.ofSeconds(expireSeconds));
}
}
private void delete(String key) {
redisHelper.delete(key);
}
public static class Builder {
RedisCache cache = new RedisCache();
public Builder cacheName(String cacheName) {
cache.cacheName = cacheName;
cache.redisHelper = SpringUtils.getBean(RedisHelper.class);
return this;
}
public RedisCache build() {
return cache;
}
}
}