publicvoidset(String key, Object value, Long time, TimeUnit unit) { stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit); }
存储到缓存,逻辑过期
实现方法2:存储到缓存,并设置逻辑过期时间
1 2 3 4 5 6
publicvoidsetWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) { RedisDataredisData=newRedisData(); redisData.setData(value); redisData.setExpireTime(LocalDateTime.now().plus(time, unit.toChronoUnit())); stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData)); }
public <R, ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit) { Stringkey= keyPrefix + id; Stringjson= stringRedisTemplate.opsForValue().get(key);
// 缓存中有直接返回 if (!Strings.isBlank(json)) { return JSONUtil.toBean(json, type); }
// 如果命中的是空值,直接返回null if (json != null) { returnnull; }
// 不存在,去数据库中拿 Rdata= dbFallback.apply(id); // 若数据库中没有,缓存空值 if (data == null) { this.set(key, "", time, unit); returnnull; } this.set(key, data, time, unit);
public <R, ID> R queryWithMutex(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit) { Stringkey= keyPrefix + id; StringshopJson= stringRedisTemplate.opsForValue().get(key);
// 缓存中有直接返回 if (Strings.isNotBlank(shopJson)) { return JSONUtil.toBean(shopJson, type); }
// 判断命中的是否是空值,是返回null if (shopJson != null) { returnnull; }
// 4.1.获取互斥锁 StringlockKey="lock:" + keyPrefix + id; R data; try { booleanisLock= tryLock(lockKey); if (!isLock) { // 获取锁失败,休眠并重试 Thread.sleep(50); return queryWithMutex(keyPrefix, id, type, dbFallback, time, unit); } // 获取锁成功,查询数据库 data = dbFallback.apply(id); if (data == null) { set(key, "", time, unit); returnnull; } this.set(key, data, time, unit); } catch (InterruptedException e) { thrownewRuntimeException(e); }finally { unlock(lockKey); } return data; }
public <ID, R> R queryWithLogicalExpire(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit) { Stringkey= keyPrefix + id; Stringjson= stringRedisTemplate.opsForValue().get(key);
// 不存在直接返回null if (Strings.isBlank(json)) { returnnull; }