spring cache注解@Cacheable缓存穿透详解
作者:chengbinbbs 发布时间:2023-12-23 13:41:25
最近发现线上监控有个SQL调用量很大,但是方法的调用量不是很大,查看接口实现,发现接口是做了缓存操作的,使用Spring cache缓存注解结合tair实现缓存操作。
但是为啥SQL调用量这么大,难道缓存没有生效。测试发现缓存是正常的,分析了代码发现,代码存在缓存穿透的风险。
具体注解是这样的
@Cacheable(value = "storeDeliveryCoverage", key = "#sellerId + '|' + #cityCode", unless = "#result == null")
unless = "#result == null"表明接口返回值不为空的时候才缓存,如果线上有大量不合法的请求参数过来,由于为空的不会缓存起来,每次请求都打到DB上,导致DB的sql调用量巨大,给了黑客可乘之机,风险还是很大的。
找到原因之后就修改,查询结果为空的时候兜底一个null,把这句unless = "#result == null"条件去掉测试了一下,发现为空的话还是不会缓存。于是debug分析了一波源码,终于发现原来是tair的问题。
由于tair自身的特性,无法缓存null。既然无法缓存null,那我们就兜底一个空对象进去,取出来的时候把空对象转化为null。
基于这个思路我把Cache的实现改造了一下
@Override
public void put(Object key, Object value) {
if (value == null) {
// 为空的话,兜底一个空对象,防止缓存穿透(由于tair自身特性不允许缓存null对象的原因,这里缓存一个空对象)
value = new Nil();
}
if (value instanceof Serializable) {
final String tairKey = String.format("%s:%s", this.name, key);
final ResultCode resultCode = this.tairManager.put(
this.namespace,
tairKey,
(Serializable) value,
0,
this.timeout
);
if (resultCode != ResultCode.SUCCESS) {
TairSpringCache.log.error(
String.format(
"[CachePut]: unable to put %s => %s into tair due to: %s",
key,
value,
resultCode.getMessage()
)
);
}
} else {
throw new RuntimeException(
String.format(
"[CachePut]: value %s is not Serializable",
value
)
);
}
}
Nil类默认是一个空对象,这里给了个内部类:
static class Nil implements Serializable {
private static final long serialVersionUID = -9138993336039047508L;
}
取缓存的get方法实现
@Override
public ValueWrapper get(Object key) {
final String tairKey = String.format("%s:%s", this.name, key);
final Result<DataEntry> result = this.tairManager.get(this.namespace, tairKey);
if (result.isSuccess() && (result.getRc() == ResultCode.SUCCESS)) {
final Object obj = result.getValue().getValue();
// 缓存为空兜底的是Nil对象,这里返回的时候需要转为null
if (obj instanceof Nil) {
return null;
}
return () -> obj;
}
return null;
}
改好了之后,测试一下,结果发现还是没有生效,缓存没有兜底,请求都打到DB上了。
debug走一遍,看了下Cache的源码,终于发现关键问题所在(具体实现流程参考上一篇:Spring Cache- 缓存 * ( CacheInterceptor)):
private Object execute(final CacheOperationInvoker invoker, Method method, CacheOperationContexts contexts) {
// Special handling of synchronized invocation
if (contexts.isSynchronized()) {
CacheOperationContext context = contexts.get(CacheableOperation.class).iterator().next();
if (isConditionPassing(context, CacheOperationExpressionEvaluator.NO_RESULT)) {
Object key = generateKey(context, CacheOperationExpressionEvaluator.NO_RESULT);
Cache cache = context.getCaches().iterator().next();
try {
return wrapCacheValue(method, cache.get(key, new Callable<Object>() {
@Override
public Object call() throws Exception {
return unwrapReturnValue(invokeOperation(invoker));
}
}));
}
catch (Cache.ValueRetrievalException ex) {
// The invoker wraps any Throwable in a ThrowableWrapper instance so we
// can just make sure that one bubbles up the stack.
throw (CacheOperationInvoker.ThrowableWrapper) ex.getCause();
}
}
else {
// No caching required, only call the underlying method
return invokeOperation(invoker);
}
}
// 处理beforeIntercepte=true的缓存删除操作
processCacheEvicts(contexts.get(CacheEvictOperation.class), true,
CacheOperationExpressionEvaluator.NO_RESULT);
// 从缓存中查找,是否有匹配@Cacheable的缓存数据
Cache.ValueWrapper cacheHit = findCachedItem(contexts.get(CacheableOperation.class));
// 如果@Cacheable没有被缓存,那么就需要将数据缓存起来,这里将@Cacheable操作收集成CachePutRequest集合,以便后续做@CachePut缓存数据存放。
List<CachePutRequest> cachePutRequests = new LinkedList<CachePutRequest>();
if (cacheHit == null) {
collectPutRequests(contexts.get(CacheableOperation.class),
CacheOperationExpressionEvaluator.NO_RESULT, cachePutRequests);
}
Object cacheValue;
Object returnValue;
//如果没有@CachePut操作,就使用@Cacheable获取的结果(可能也没有@Cableable,所以result可能为空)。
if (cacheHit != null && cachePutRequests.isEmpty() && !hasCachePut(contexts)) {
//如果没有@CachePut操作,并且cacheHit不为空,说明命中缓存了,直接返回缓存结果
cacheValue = cacheHit.get();
returnValue = wrapCacheValue(method, cacheValue);
}
else {
// 否则执行具体方法内容,返回缓存的结果
returnValue = invokeOperation(invoker);
cacheValue = unwrapReturnValue(returnValue);
}
// Collect any explicit @CachePuts
collectPutRequests(contexts.get(CachePutOperation.class), cacheValue, cachePutRequests);
// Process any collected put requests, either from @CachePut or a @Cacheable miss
for (CachePutRequest cachePutRequest : cachePutRequests) {
cachePutRequest.apply(cacheValue);
}
// Process any late evictions
processCacheEvicts(contexts.get(CacheEvictOperation.class), false, cacheValue);
return returnValue;
}
根据key从缓存中查找,返回的结果是ValueWrapper,它是返回结果的包装器:
private Cache.ValueWrapper findCachedItem(Collection<CacheOperationContext> contexts) {
Object result = CacheOperationExpressionEvaluator.NO_RESULT;
for (CacheOperationContext context : contexts) {
if (isConditionPassing(context, result)) {
Object key = generateKey(context, result);
Cache.ValueWrapper cached = findInCaches(context, key);
if (cached != null) {
return cached;
}
else {
if (logger.isTraceEnabled()) {
logger.trace("No cache entry for key '" + key + "' in cache(s) " + context.getCacheNames());
}
}
}
}
return null;
}
private Cache.ValueWrapper findInCaches(CacheOperationContext context, Object key) {
for (Cache cache : context.getCaches()) {
Cache.ValueWrapper wrapper = doGet(cache, key);
if (wrapper != null) {
if (logger.isTraceEnabled()) {
logger.trace("Cache entry for key '" + key + "' found in cache '" + cache.getName() + "'");
}
return wrapper;
}
}
return null;
}
这里判断缓存是否命中的逻辑是根据cacheHit是否为空,而cacheHit是ValueWrapper类型,查看ValueWrapper是一个接口,它的实现类是SimpleValueWrapper,这是一个包装器,将缓存的结果包装起来了。
而我们前面的get方法取缓存的时候如果为Nil对象,返回的是null,这样缓存判断出来是没有命中,即cacheHit==null,就会去执行具体方法朔源。
所以到这里已经很清晰了,关键问题是get取缓存的结果如果是兜底的Nil对象,应该返回new SimpleValueWrapper(null)。
应该返回包装器,包装的是缓存的对象为null。
测试了一下,发现ok了
具体源码如下:
/**
* 基于tair的缓存,适配spring缓存框架
*/
public class TairSpringCache implements Cache {
private static final Logger log = LoggerFactory.getLogger(TairSpringCache.class);
private TairManager tairManager;
private final String name;
private int namespace;
private int timeout;
public TairSpringCache(String name, TairManager tairManager, int namespace) {
this(name, tairManager, namespace, 0);
}
public TairSpringCache(String name, TairManager tairManager, int namespace, int timeout) {
this.name = name;
this.tairManager = tairManager;
this.namespace = namespace;
this.timeout = timeout;
}
@Override
public String getName() {
return this.name;
}
@Override
public Object getNativeCache() {
return this.tairManager;
}
@Override
public ValueWrapper get(Object key) {
final String tairKey = String.format("%s:%s", this.name, key);
final Result<DataEntry> result = this.tairManager.get(this.namespace, tairKey);
if (result.isSuccess() && (result.getRc() == ResultCode.SUCCESS)) {
final Object obj = result.getValue().getValue();
// 缓存为空兜底的是Nil对象,这里返回的时候需要转为null
if (obj instanceof Nil) {
return () -> null;
}
return () -> obj;
}
return null;
}
@Override
public <T> T get(Object key, Class<T> type) {
return (T) this.get(key).get();
}
public <T> T get(Object o, Callable<T> callable) {
return null;
}
@Override
public void put(Object key, Object value) {
if (value == null) {
// 为空的话,兜底一个空对象,防止缓存穿透(由于tair自身特性不允许缓存null对象的原因,这里缓存一个空对象)
value = new Nil();
}
if (value instanceof Serializable) {
final String tairKey = String.format("%s:%s", this.name, key);
final ResultCode resultCode = this.tairManager.put(
this.namespace,
tairKey,
(Serializable) value,
0,
this.timeout
);
if (resultCode != ResultCode.SUCCESS) {
TairSpringCache.log.error(
String.format(
"[CachePut]: unable to put %s => %s into tair due to: %s",
key,
value,
resultCode.getMessage()
)
);
}
} else {
throw new RuntimeException(
String.format(
"[CachePut]: value %s is not Serializable",
value
)
);
}
}
public ValueWrapper putIfAbsent(Object key, Object value) {
final ValueWrapper vw = this.get(key);
if (vw.get() == null) {
this.put(key, value);
}
return vw;
}
@Override
public void evict(Object key) {
final String tairKey = String.format("%s:%s", this.name, key);
final ResultCode resultCode = this.tairManager.delete(this.namespace, tairKey);
if ((resultCode == ResultCode.SUCCESS)
|| (resultCode == ResultCode.DATANOTEXSITS)
|| (resultCode == ResultCode.DATAEXPIRED)) {
return;
}
else {
final String errMsg = String.format(
"[CacheDelete]: unable to evict key %s, resultCode: %s",
key,
resultCode
);
TairSpringCache.log.error(errMsg);
throw new RuntimeException(errMsg);
}
}
@Override
public void clear() {
//TODO fgz: implement here later
}
public void setTairManager(TairManager tairManager) {
this.tairManager = tairManager;
}
public void setNamespace(int namespace) {
this.namespace = namespace;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
static class Nil implements Serializable {
private static final long serialVersionUID = -9138993336039047508L;
}
}
测试用例就不贴了。
来源:https://blog.csdn.net/chengbinbbs/article/details/88393102
猜你喜欢
- 使用Mybatis的开发者,大多数都会遇到一个问题,就是要写大量的SQL在xml文件中,除了特殊的业务逻辑SQL之外,还有大量结构类似的增删
- spring FactoryBean 是创建 复杂的bean,一般的bean 直接用xml配置即可,如果一个bean的创建过程中
- 当我们在项目中登录使用验证码的时候,不妨试试Kaptcha生成验证码,非常简单1、首先,我们在pom.xml文件中引入kaptcha的mav
- 由于之前一直在使用spring-boot开发,但一直苦恼于不知道如何利用debug调试代码.在网上查找了很多文章之后。学习之余决定把spri
- 前言由于现在网络层已经升级到RxJava2.x相关的了,所以需要做些调整。虽然RxJava1.x和RxJava2.x同属RxJava系列,但
- 读写锁:分为读锁和写锁,多个读锁不互斥,读锁与写锁互斥,这是由jvm自己控制的,你只要上好相应的锁即可。如果你的代码只读数据,可以很多人同时
- Java内部类一、 含义在Java编程语言里,程序是由类(class)构建而成的。在一个类的内部也可以声明类,我们把这样的类叫做内部类。二、
- 问题描述问题原因出现该问题的原因是项目Project当中的jdk与电脑当中的jdk版本不一致造成的。解决方法1、查看本机的jdk版本:命令提
- 本文实例讲述了C#获取网页源代码的方法。分享给大家供大家参考。具体如下:public string GetPageHTML(string u
- 前言最近,在给项目组使用Spring搭建Java项目基础框架时,发现使用Spring提供的BeanPostProcessor可以很简单方便地
- Spring 使用Junit单元测试并配置数据源一、问题描述由于公司项目中的数据源是配置在Tomcat中的server.xml中的,所以在使
- 此项目使用了OpenCVSharp加载本地摄像头,多个摄像头支持切换展示,也可以展示rtsp地址。使用NuGet如下:代码如下一、创建Mai
- 项目中用到用户定义运算公式进行就算的需求,这样需要进行字符串四则运算解析,下面提供字符串公式四则运算解析与计算工具类,需要的同学可参考。工具
- 使用的是idea+restful风格第一:引入依赖为:<!--poi--> <dependenc
- 前文传送门:Netty启动流程服务端channel初始化注册多路复用回到上一小节的代码:final ChannelFuture initAn
- 最近一个项目中,需要用到Java的websocket新特性,于是就学了一下,感觉这技术还挺好玩的,瞬间知道网页上面的那些在线客服是怎么做的了
- 原理分析:迅雷的thunder://地址就是将普通url地址加前缀‘AA'、后缀‘ZZ',再base64编码后得到的字符串实
- 本文实例讲述了Java二维数组简单定义与使用方法。分享给大家供大家参考,具体如下:Java的二维数组是先创建一个一维数组,然后该数组的元素再
- Lombok简介和其他语言相比,Java经常因为不必要的冗长被批评。Lombok提供了一系列注解用以在后台生成模板代码,将其从你的类中删除,
- JAVA用于开发图形界面应用的 SWING 组件包功能强大,使用方便。接下来我们就使用其写一个简单的图形界面小程序:加法计算器。第一步:首先