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 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
| @Component @Slf4j public class CacheClient {
private final StringRedisTemplate stringRedisTemplate;
public CacheClient(StringRedisTemplate redisTemplate) { this.stringRedisTemplate = redisTemplate; }
public void set(String key, Object value, Long time, TimeUnit unit){
String data = JSONUtil.toJsonStr(value);
stringRedisTemplate.opsForValue().set(key,data,time,unit);
}
public void setWithLogicalExpire(String key,Object value,Long time,TimeUnit unit){
RedisData data = new RedisData(); data.setData(value); data.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
String jsonStr = JSONUtil.toJsonStr(data); stringRedisTemplate.opsForValue().set(key,jsonStr); }
public <R,ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type ,Function<ID,R> dbFallback,Long time,TimeUnit unit){
String key = keyPrefix + id;
String json = stringRedisTemplate.opsForValue().get(key); if(StrUtil.isNotBlank(json)){
R bean = JSONUtil.toBean(json, type); return bean; } if(json != null){
return null; }
R r = dbFallback.apply(id); if(r == null){
stringRedisTemplate.opsForValue().set(key,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES); throw new RuntimeException("未命中,内存存入空数据"); }
stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(r),time,unit); return r; }
private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
public <R,ID> R queryWithLogicalExpire(String keyPrefix, ID id, Class<R> type ,Function<ID,R> dbFallback,Long time,TimeUnit unit){
String key = keyPrefix + id; String json = stringRedisTemplate.opsForValue().get(key); if(StrUtil.isBlank(json)){ return null; }
RedisData redisData = JSONUtil.toBean(json, RedisData.class); Object data = redisData.getData(); R r = JSONUtil.toBean((JSONObject) data, type); LocalDateTime expireTime = redisData.getExpireTime(); if(expireTime.isAfter(LocalDateTime.now())){
return r; }
String lockKey = RedisConstants.LOCK_SHOP_KEY + id; boolean isLock = tryLock(lockKey);
if(isLock){
CACHE_REBUILD_EXECUTOR.submit(() ->{ try{
R r1 = dbFallback.apply(id);
this.setWithLogicalExpire(key,r1,time,unit); }catch (Exception e){ throw new RuntimeException(e); }finally{
unLock(key); } });
}
return r; }
private boolean tryLock(String key){ Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
return BooleanUtil.isTrue(b); }
private void unLock(String key){ stringRedisTemplate.delete(key); }
}
|