通过缓存空对象解决缓存穿透问题
1 2 3 4 5 6 7 8 9 10 11 12
| @Override public Result queryById(Long id) {
Shop shop = queryWithPassThrough(id);
if(shop==null){ return Result.fail("店铺信息不存在"); }
return Result.ok(shop); }
|
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
| public Shop queryWithPassThrough(Long id){
String shopJson = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
if(StrUtil.isNotBlank(shopJson)){ return JSONUtil.toBean(shopJson, Shop.class); }
if(shopJson!=null){ return null; }
Shop shop = getById(id);
if(shop==null){ stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES); return null; }
stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+ id,JSONUtil.toJsonStr(shop),RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
return shop; }
|

代码是缓存空对象解决缓存穿透的思路,图中另一个是加了布隆过滤器的解决方案
大体思路:
