背景
缓存穿透是指客户端请求的数据在缓存中和数据库中都不存在,这样缓存永远不会生效,这些请求都会打到数据库
常见的解决方案有两种,分别是缓存空对象和布隆过滤器
1.缓存空对象
优点:实现简单,维护方便
缺点:额外的内存消耗、可能造成短期的不一致
2.布隆过滤器
优点:内存占用较少,没有多余key
缺点:实现复杂、存在误判可能
代码实现
前置
这里以根据 id 查询商品店铺为案例
实体类
@data @equalsandhashcode(callsuper = false) @accessors(chain = true) @tablename("tb_shop") public class shop implements serializable { private static final long serialversionuid = 1l; /** * 主键 */ @tableid(value = "id", type = idtype.auto) private long id; /** * 商铺名称 */ private string name; /** * 商铺类型的id */ private long typeid; /** * 商铺图片,多个图片以','隔开 */ private string images; /** * 商圈,例如陆家嘴 */ private string area; /** * 地址 */ private string address; /** * 经度 */ private double x; /** * 维度 */ private double y; /** * 均价,取整数 */ private long avgprice; /** * 销量 */ private integer sold; /** * 评论数量 */ private integer comments; /** * 评分,1~5分,乘10保存,避免小数 */ private integer score; /** * 营业时间,例如 10:00-22:00 */ private string openhours; /** * 创建时间 */ private localdatetime createtime; /** * 更新时间 */ private localdatetime updatetime; @tablefield(exist = false) private double distance; }
常量类
public class redisconstants { public static final long cache_null_ttl = 2l; public static final long cache_shop_ttl = 30l; public static final string cache_shop_key = "cache:shop:"; }
工具类
public class objectmaputils { // 将对象转为 map public static map<string, string> obj2map(object obj) throws illegalaccessexception { map<string, string> result = new hashmap<>(); class<?> clazz = obj.getclass(); field[] fields = clazz.getdeclaredfields(); for (field field : fields) { // 如果为 static 且 final 则跳过 if (modifier.isstatic(field.getmodifiers()) && modifier.isfinal(field.getmodifiers())) { continue; } field.setaccessible(true); // 设置为可访问私有字段 object fieldvalue = field.get(obj); if (fieldvalue != null) { result.put(field.getname(), field.get(obj).tostring()); } } return result; } // 将 map 转为对象 public static object map2obj(map<object, object> map, class<?> clazz) throws exception { object obj = clazz.getdeclaredconstructor().newinstance(); for (map.entry<object, object> entry : map.entryset()) { object fieldname = entry.getkey(); object fieldvalue = entry.getvalue(); field field = clazz.getdeclaredfield(fieldname.tostring()); field.setaccessible(true); // 设置为可访问私有字段 string fieldvaluestr = fieldvalue.tostring(); // 根据字段类型进行转换 if (field.gettype().equals(int.class) || field.gettype().equals(integer.class)) { field.set(obj, integer.parseint(fieldvaluestr)); } else if (field.gettype().equals(boolean.class) || field.gettype().equals(boolean.class)) { field.set(obj, boolean.parseboolean(fieldvaluestr)); } else if (field.gettype().equals(double.class) || field.gettype().equals(double.class)) { field.set(obj, double.parsedouble(fieldvaluestr)); } else if (field.gettype().equals(long.class) || field.gettype().equals(long.class)) { field.set(obj, long.parselong(fieldvaluestr)); } else if (field.gettype().equals(string.class)) { field.set(obj, fieldvaluestr); } else if(field.gettype().equals(localdatetime.class)) { field.set(obj, localdatetime.parse(fieldvaluestr)); } } return obj; } }
结果返回类
@data @noargsconstructor @allargsconstructor public class result { private boolean success; private string errormsg; private object data; private long total; public static result ok(){ return new result(true, null, null, null); } public static result ok(object data){ return new result(true, null, data, null); } public static result ok(list<?> data, long total){ return new result(true, null, data, total); } public static result fail(string errormsg){ return new result(false, errormsg, null, null); } }
控制层
@restcontroller @requestmapping("/shop") public class shopcontroller { @resource public ishopservice shopservice; /** * 根据id查询商铺信息 * @param id 商铺id * @return 商铺详情数据 */ @getmapping("/{id}") public result queryshopbyid(@pathvariable("id") long id) { return shopservice.queryshopbyid(id); } /** * 新增商铺信息 * @param shop 商铺数据 * @return 商铺id */ @postmapping public result saveshop(@requestbody shop shop) { return shopservice.saveshop(shop); } /** * 更新商铺信息 * @param shop 商铺数据 * @return 无 */ @putmapping public result updateshop(@requestbody shop shop) { return shopservice.updateshop(shop); } }
缓存空对象
流程图为:
服务层代码:
public result queryshopbyid(long id) { // 从 redis 查询 string shopkey = redisconstants.cache_shop_key + id; map<object, object> entries = redistemplate.opsforhash().entries(shopkey); // 缓存命中 if(!entries.isempty()) { try { // 如果是空对象,表示一定不存在数据库中,直接返回(解决缓存穿透) if(entries.containskey("")) { return result.fail("店铺不存在"); } // 刷新有效期 redistemplate.expire(shopkey, redisconstants.cache_shop_ttl, timeunit.minutes); shop shop = (shop) objectmaputils.map2obj(entries, shop.class); return result.ok(shop); } catch (exception e) { throw new runtimeexception(e); } } // 查询数据库 shop shop = this.getbyid(id); if(shop == null) { // 存入空值 redistemplate.opsforhash().put(shopkey, "", ""); redistemplate.expire(shopkey, redisconstants.cache_null_ttl, timeunit.minutes); // 不存在,直接返回 return result.fail("店铺不存在"); } // 存在,写入 redis try { redistemplate.opsforhash().putall(shopkey, objectmaputils.obj2map(shop)); redistemplate.expire(shopkey, redisconstants.cache_shop_ttl, timeunit.minutes); } catch (illegalaccessexception e) { throw new runtimeexception(e); } return result.ok(shop); }
布隆过滤器
这里选择使用布隆过滤器存储存在于数据库中的 id,原因在于,如果存储了不存在于数据库中的 id,首先由于 id 的取值范围很大,那么不存在的 id 有很多,因此更占用空间;其次,由于布隆过滤器有一定的误判率,那么可能导致少数原本存在于数据库中的 id 被判为了不存在,然后直接返回了,此时就会出现根本性的正确性错误。相反,如果存储的是数据库中存在的 id,那么即使少数不存在的 id 被判为了存在,由于数据库中确实没有对应的 id,那么也会返回空,最终结果还是正确的
这里使用 guava 依赖的布隆过滤器
依赖为:
<dependency> <groupid>com.google.guava</groupid> <artifactid>guava</artifactid> <version>30.1.1-jre</version> </dependency>
封装了布隆过滤器的类(注意初始化时要把数据库中已有的 id 加入布隆过滤器):
public class shopbloomfilter { private bloomfilter<long> bloomfilter; public shopbloomfilter(shopmapper shopmapper) { // 初始化布隆过滤器,设计预计元素数量为100_0000l,误差率为1% bloomfilter = bloomfilter.create(funnels.longfunnel(), 100_0000, 0.01); // 将数据库中已有的店铺 id 加入布隆过滤器 list<shop> shops = shopmapper.selectlist(null); for (shop shop : shops) { bloomfilter.put(shop.getid()); } } public void add(long id) { bloomfilter.put(id); } public boolean mightcontain(long id){ return bloomfilter.mightcontain(id); } }
对应的配置类(将其设置为 bean)
@configuration public class bloomconfig { @bean public shopbloomfilter shopbloomfilter(shopmapper shopmapper) { return new shopbloomfilter(shopmapper); } }
首先要修改查询方法,在根据 id 查询时,如果对应 id 不在布隆过滤器中,则直接返回。然后还要修改保存方法,在保存的时候还需要将对应的 id 加入布隆过滤器中
@override public result queryshopbyid(long id) { // 如果不在布隆过滤器中,直接返回 if(!shopbloomfilter.mightcontain(id)) { return result.fail("店铺不存在"); } // 从 redis 查询 string shopkey = redisconstants.cache_shop_key + id; map<object, object> entries = redistemplate.opsforhash().entries(shopkey); // 缓存命中 if(!entries.isempty()) { try { // 刷新有效期 redistemplate.expire(shopkey, redisconstants.cache_shop_ttl, timeunit.minutes); shop shop = (shop) objectmaputils.map2obj(entries, shop.class); return result.ok(shop); } catch (exception e) { throw new runtimeexception(e); } } // 查询数据库 shop shop = this.getbyid(id); if(shop == null) { // 不存在,直接返回 return result.fail("店铺不存在"); } // 存在,写入 redis try { redistemplate.opsforhash().putall(shopkey, objectmaputils.obj2map(shop)); redistemplate.expire(shopkey, redisconstants.cache_shop_ttl, timeunit.minutes); } catch (illegalaccessexception e) { throw new runtimeexception(e); } return result.ok(shop); } @override public result saveshop(shop shop) { // 写入数据库 this.save(shop); // 将 id 写入布隆过滤器 shopbloomfilter.add(shop.getid()); // 返回店铺 id return result.ok(shop.getid()); }
结合两种方法
由于布隆过滤器有一定的误判率,所以这里可以进一步优化,如果出现误判情况,即原本不存在于数据库中的 id 被判为了存在,就用缓存空对象的方式将其缓存到 redis 中
@override public result queryshopbyid(long id) { // 如果不在布隆过滤器中,直接返回 if(!shopbloomfilter.mightcontain(id)) { return result.fail("店铺不存在"); } // 从 redis 查询 string shopkey = redisconstants.cache_shop_key + id; map<object, object> entries = redistemplate.opsforhash().entries(shopkey); // 缓存命中 if(!entries.isempty()) { try { // 如果是空对象,表示一定不存在数据库中,直接返回(解决缓存穿透) if(entries.containskey("")) { return result.fail("店铺不存在"); } // 刷新有效期 redistemplate.expire(shopkey, redisconstants.cache_shop_ttl, timeunit.minutes); shop shop = (shop) objectmaputils.map2obj(entries, shop.class); return result.ok(shop); } catch (exception e) { throw new runtimeexception(e); } } // 查询数据库 shop shop = this.getbyid(id); if(shop == null) { // 存入空值 redistemplate.opsforhash().put(shopkey, "", ""); redistemplate.expire(shopkey, redisconstants.cache_null_ttl, timeunit.minutes); // 不存在,直接返回 return result.fail("店铺不存在"); } // 存在,写入 redis try { redistemplate.opsforhash().putall(shopkey, objectmaputils.obj2map(shop)); redistemplate.expire(shopkey, redisconstants.cache_shop_ttl, timeunit.minutes); } catch (illegalaccessexception e) { throw new runtimeexception(e); } return result.ok(shop); }
到此这篇关于解决redis缓存穿透(缓存空对象、布隆过滤器)的文章就介绍到这了,更多相关redis缓存穿透内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论