缓存穿透是指缓存和数据库中都没有的数据,而用户不断发起请求,如发起为id为“-1”的数据或id为特别大不存在的数据。这时的用户很可能是攻击者,攻击会导致数据库压力过大。
可见缓存穿透会对系统造成多在的隐患。 若一个操作数据库的ORM工具,能有抵御缓存穿透的能力,变会使我们的系统更加安全,也避免我们自己开发该功能耗时耗力!
以下,测试一个具有抵御缓存穿透能力的ORM框架Bee.
测试一级缓存和二级Redis缓存的抵御缓存穿透的能力。
/*
* Copyright 2016-2021 the original author.All rights reserved.
* Kingstar(honeysoft@126.com)
* The license,see the LICENSE file.
*/
package org.teasoft.exam.bee.osql.special;
import org.teasoft.bee.osql.Suid;
import org.teasoft.bee.osql.SuidRich;
import org.teasoft.exam.bee.osql.entity.TestUser;
import org.teasoft.honey.osql.core.HoneyConfig;
import org.teasoft.honey.osql.shortcut.BF;
/**
* 测试缓存穿透.Bee默认能抵御缓存穿透
* @author Kingstar
* @since 1.11
*/
public class NullUseCache {
public static void main(String[] args) {
test();
}
public static void test() {
try {
HoneyConfig.getHoneyConfig().cache_timeout=10; //20毫秒
HoneyConfig.getHoneyConfig().cache_levelTwoTimeout=6; //6秒
// HoneyContext.setConfigRefresh(true); //没有触发机会
// Cache cache=new BeeExtRedisCache();
// BeeFactory.getHoneyFactory().setCache(cache);
Suid suid = BF.getSuid();
TestUser testUser=new TestUser();
testUser.setId(0L);
suid.select(testUser);
suid.select(testUser); // test whether use cache
SuidRich suidRich = BF.getSuidRich();
suidRich.selectById(new TestUser(), -1L);
suidRich.selectById(new TestUser(), -1L);
//放在这没用.要放到第一个查询前.
// HoneyConfig.getHoneyConfig().cache_timeout=20; //20毫秒
// HoneyConfig.getHoneyConfig().cache_levelTwoTimeout=6; //6秒
HoneyContext.setConfigRefresh(true); //没有触发机会
//测试二级缓存的抵御缓存穿透能力
suidRich.selectById(new TestUser(), -1L);
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
suidRich.selectById(new TestUser(), -1L);
} catch (Exception e) {
e.printStackTrace();
}
}
}