一次排查@CacheEvict注解失效的经历及解决

目录
  • 排查@CacheEvict注解失效
    • 下面是我通过源码跟踪排查问题的过程
    • 小结一下
  • 说说spring全家桶中@CacheEvict无效情况
    • 举个例子

排查@CacheEvict注解失效

我简单看了一下《Spring实战》中的demo,然后就应用到业务代码中了,本以为如此简单的事情,竟然在代码提交后的1个周,被同事发现。selectByTaskId()方法查出来的数据总是过时的。

代码如下:

@Cacheable("taskParamsCache")
List<TaskParams> selectByTaskId(Long taskId);
// ...
// ...
@CacheEvict("taskParamsCache")
int deleteByTaskId(Long taskId);

想要的效果是当程序调用selectByTaskId()方法时,把结果缓存下来,然后在调用deleteByTaskId()方法时,将缓存清空。

经过数据库数据对比之后,把问题排查的方向定位在@CacheEvict注解失效了。

下面是我通过源码跟踪排查问题的过程

在deleteByTaskId()方法的调用出打断点,跟进代码到spring生成的代理层。

@Override
		@Nullable
		public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
			Object oldProxy = null;
			boolean setProxyContext = false;
			Object target = null;
			TargetSource targetSource = this.advised.getTargetSource();
			try {
				if (this.advised.exposeProxy) {
					// Make invocation available if necessary.
					oldProxy = AopContext.setCurrentProxy(proxy);
					setProxyContext = true;
				}
				// Get as late as possible to minimize the time we "own" the target, in case it comes from a pool...
				target = targetSource.getTarget();
				Class<?> targetClass = (target != null ? target.getClass() : null);
				List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
				Object retVal;
				// Check whether we only have one InvokerInterceptor: that is,
				// no real advice, but just reflective invocation of the target.
				if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {
					// We can skip creating a MethodInvocation: just invoke the target directly.
					// Note that the final invoker must be an InvokerInterceptor, so we know
					// it does nothing but a reflective operation on the target, and no hot
					// swapping or fancy proxying.
					Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
					retVal = methodProxy.invoke(target, argsToUse);
				}
				else {
					// We need to create a method invocation...
					retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
				}
				retVal = processReturnType(proxy, target, method, retVal);
				return retVal;
			}
			finally {
				if (target != null && !targetSource.isStatic()) {
					targetSource.releaseTarget(target);
				}
				if (setProxyContext) {
					// Restore old proxy.
					AopContext.setCurrentProxy(oldProxy);
				}
			}
		}

通过getInterceptorsAndDynamicInterceptionAdvice获取到当前方法的拦截器,里面包含了CacheIneterceptor,说明注解被spring检测到了。

进入CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed()方法内部

org.springframework.aop.framework.ReflectiveMethodInvocation#proceed

@Override
	@Nullable
	public Object proceed() throws Throwable {
		//	We start with an index of -1 and increment early.
		if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
			return invokeJoinpoint();
		}
		Object interceptorOrInterceptionAdvice =
				this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
		if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
			// Evaluate dynamic method matcher here: static part will already have
			// been evaluated and found to match.
			InterceptorAndDynamicMethodMatcher dm =
					(InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
			if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {
				return dm.interceptor.invoke(this);
			}
			else {
				// Dynamic matching failed.
				// Skip this interceptor and invoke the next in the chain.
				return proceed();
			}
		}
		else {
			// It's an interceptor, so we just invoke it: The pointcut will have
			// been evaluated statically before this object was constructed.
			return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
		}
	}

this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex)方法取第一个拦截器,正是我们要关注的CacheIneterceptor,然后调用((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this)方法,继续跟进

org.springframework.cache.interceptor.CacheInterceptor#invoke

@Override
	@Nullable
	public Object invoke(final MethodInvocation invocation) throws Throwable {
		Method method = invocation.getMethod();
		CacheOperationInvoker aopAllianceInvoker = () -> {
			try {
				return invocation.proceed();
			}
			catch (Throwable ex) {
				throw new CacheOperationInvoker.ThrowableWrapper(ex);
			}
		};
		try {
			return execute(aopAllianceInvoker, invocation.getThis(), method, invocation.getArguments());
		}
		catch (CacheOperationInvoker.ThrowableWrapper th) {
			throw th.getOriginal();
		}
	}

进入execute方法

protected Object execute(CacheOperationInvoker invoker, Object target, Method method, Object[] args) {
		// Check whether aspect is enabled (to cope with cases where the AJ is pulled in automatically)
		if (this.initialized) {
			Class<?> targetClass = getTargetClass(target);
			CacheOperationSource cacheOperationSource = getCacheOperationSource();
			if (cacheOperationSource != null) {
				Collection<CacheOperation> operations = cacheOperationSource.getCacheOperations(method, targetClass);
				if (!CollectionUtils.isEmpty(operations)) {
					return execute(invoker, method,
							new CacheOperationContexts(operations, method, args, target, targetClass));
				}
			}
		}
		return invoker.invoke();
	}

cacheOperationSource记录系统中所有使用了缓存的方法,cacheOperationSource.getCacheOperations(method, targetClass)能获取deleteByTaskId()方法缓存元数据,然后执行execute()方法

@Nullable
	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, () -> 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);
			}
		}
		// Process any early evictions
		processCacheEvicts(contexts.get(CacheEvictOperation.class), true,
				CacheOperationExpressionEvaluator.NO_RESULT);
		// Check if we have a cached item matching the conditions
		Cache.ValueWrapper cacheHit = findCachedItem(contexts.get(CacheableOperation.class));
		// Collect puts from any @Cacheable miss, if no cached item is found
		List<CachePutRequest> cachePutRequests = new LinkedList<>();
		if (cacheHit == null) {
			collectPutRequests(contexts.get(CacheableOperation.class),
					CacheOperationExpressionEvaluator.NO_RESULT, cachePutRequests);
		}
		Object cacheValue;
		Object returnValue;
		if (cacheHit != null && cachePutRequests.isEmpty() && !hasCachePut(contexts)) {
			// If there are no put requests, just use the cache hit
			cacheValue = cacheHit.get();
			returnValue = wrapCacheValue(method, cacheValue);
		}
		else {
			// Invoke the method if we don't have a cache hit
			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;
	}

这里大致过程是:

先执行beforInvokeEvict ---- 执行数据库delete操作 --- 执行CachePut操作 ---- 执行afterInvokeEvict

我们的注解是方法调用后再使缓存失效,直接所以有效的操作应在倒数第2行

private void performCacheEvict(
			CacheOperationContext context, CacheEvictOperation operation, @Nullable Object result) {
		Object key = null;
		for (Cache cache : context.getCaches()) {
			if (operation.isCacheWide()) {
				logInvalidating(context, operation, null);
				doClear(cache);
			}
			else {
				if (key == null) {
					key = generateKey(context, result);
				}
				logInvalidating(context, operation, key);
				doEvict(cache, key);
			}
		}
	}

这里通过context.getCaches()获取到name为taskParamsCache的缓存

然后generateKey生成key,注意这里,发现生成的key是com.xxx.xxx.atomic.impl.xxxxdeleteByTaskId982,但是缓存中的key却是com.xxx.xxx.atomic.impl.xxxxselectByTaskId982,下面调用的doEvict(cache, key)方法不再跟进了,就是从cache中移除key对应值。明显这里key对应不上的,这也是导致@CacheEvict没有生效的原因。

小结一下

我还是太大意了,当时看了注解@CacheEvict的对key的注释:

大意就是如果没有指定key,那就会使用方法所有参数生成一个key,明显com.xxx.xxx.atomic.impl.xxxxselectByTaskId982是方法名 + 参数,可是你没说把方法名还加上了啊,说好的只用参数呢,哈哈,这个bug是我使用不当引出的,很多人不会犯这种低级错误。

解决办法就是使用SpEL明确定义key

@Cacheable(value = "taskParamsCache", key = "#taskId")
List<TaskParams> selectByTaskId(Long taskId);
// ...
// ...
@CacheEvict(value = "taskParamsCache", key = "#taskId")
int deleteByTaskId(Long taskId);

说说spring全家桶中@CacheEvict无效情况

@CacheEvict(value =“test”, allEntries = true)

1、使用@CacheEvict注解的方法必须是controller层直接调用,service里间接调用不生效。

2、原因是因为key值跟你查询方法的key值不统一,所以导致缓存并没有清除

3、把@CacheEvict的方法和@Cache的方法放到一个java文件中写,他俩在两个java文件的话,会导致@CacheEvict失效。

4、返回值必须设置为void

@CacheEvict annotation

It is important to note that void methods can be used with @CacheEvict

5、@CacheEvict必须作用在走代理的方法上

在使用Spring @CacheEvict注解的时候,要注意,如果类A的方法f1()被标注了 @CacheEvict注解,那么当类A的其他方法,例如:f2(),去直接调用f1()的时候, @CacheEvict是不起作用的,原因是 @CacheEvict是基于Spring AOP代理类,f2()属于内部方法,直接调用f1()时,是不走代理的。

举个例子

不生效:

@Override
public void saveEntity(Menu menu) {
  try {
    mapper.insert(menu);
    //Cacheable 不生效
    this.test();
  }catch(Exception e){
    e.printStackTrace();
  }
}
@CacheEvict(value = "test" , allEntries = true)
public void test() {
}

正确使用:

@Override
@CacheEvict(value = "test" , allEntries = true)
public void saveEntity(Menu menu) {
  try {
    mapper.insert(menu);
  }catch(Exception e){
    e.printStackTrace();
  }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • @CacheEvict + redis实现批量删除缓存

    目录 @CacheEvict + redis批量删除缓存 一.@Cacheable注解 二.@CacheEvict注解 三.批量删除缓存 四.代码 @CacheEvict清除指定下所有缓存 @CacheEvict + redis批量删除缓存 一.@Cacheable注解 添加缓存. /** * @Cacheable * 将方法的运行结果进行缓存:以后再要相同的数据,直接从缓存中获取,不用调用方法: * CacheManager管理多个Cache组件,对缓存的真正CRUD操作在Cache组件中,每

  • @CacheEvict 清除多个key的实现方式

    借用@Caching实现 入参是基本类型的: @Caching(evict={@CacheEvict(value = Cache.CONSTANT, key = "'" + CacheKey.SINGLE_ROLE_NAME + "'+#roleId"), @CacheEvict(value = Cache.CONSTANT, key = "'" + CacheKey.ROLES_NAME + "'+#roleId"), @C

  • 详解Spring缓存注解@Cacheable,@CachePut , @CacheEvict使用

    注释介绍 @Cacheable @Cacheable 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存 @Cacheable 作用和配置方法 参数 解释 example value 缓存的名称,在 spring 配置文件中定义,必须指定至少一个 例如: @Cacheable(value="mycache") @Cacheable(value={"cache1","cache2"} key 缓存的 key,可以为空,如果指定要按照

  • @CacheEvict中的allEntries与beforeInvocation的区别说明

    目录 @CacheEvict allEntries与beforeInvocation区别 @CacheEvict注解参数详解 1.value 2. allEntries 3.beforeInvocation 4.condition 5.key 6.cacheNames @CacheEvict allEntries与beforeInvocation区别 在spring cache中,@CacheEvict是清除缓存的注解. 其中注解参数可以只有value,key意思是清除在value值空间中的ke

  • 使用@CacheEvict清除指定下所有缓存

    目录 @CacheEvict清除指定下所有缓存 @Cacheable 缓存 @CachePut:缓存更新 @CacheEvict:缓存删除 @Cacheable 缓存 @CachePut:缓存更新 @CacheEvict:缓存删除 @CacheEvict清除指定下所有缓存 @CacheEvict(cacheNames = "parts:grid",allEntries = true) 此注解会清除part:grid下所有缓存 @CacheEvict要求指定一个或多个缓存,使之都受影响.

  • spring整合redis缓存并以注解(@Cacheable、@CachePut、@CacheEvict)形式使用

    maven项目中在pom.xml中依赖2个jar包,其他的spring的jar包省略: <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.8.1</version> </dependency> <dependency> <groupId>org.springfra

  • 一次排查@CacheEvict注解失效的经历及解决

    目录 排查@CacheEvict注解失效 下面是我通过源码跟踪排查问题的过程 小结一下 说说spring全家桶中@CacheEvict无效情况 举个例子 排查@CacheEvict注解失效 我简单看了一下<Spring实战>中的demo,然后就应用到业务代码中了,本以为如此简单的事情,竟然在代码提交后的1个周,被同事发现.selectByTaskId()方法查出来的数据总是过时的. 代码如下: @Cacheable("taskParamsCache") List<Ta

  • SpringBoot使用Async注解失效原因分析及解决(spring异步回调)

    目录 Async注解失效原因分析及解决(spring异步回调) Spring中@Async 有时候在使用的过程中@Async注解会失效 解决方式一 解决方式二 springboot @Async 失效可能原因 Async注解失效原因分析及解决(spring异步回调) Spring中@Async 在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的:但是在处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用多线程来完成此类任务,其实,在spring 3.x之后,就已

  • SpringBoot调用公共模块的自定义注解失效的解决

    目录 调用公共模块的自定义注解失效 项目结构如下 解决方法 SpringBoot注解不生效,踩坑 解决方法 调用公共模块的自定义注解失效 项目结构如下 我在 bi-common 公共模块里定义了一个自定义注解,实现AOP记录日志,bi-batch 项目已引用了 bi-common ,当在 bi-batch 使用注解的时候,没有报错,但是切面却失效. 自定义注解: @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) pub

  • Spring @Transactional注解失效解决方案

    这篇文章主要介绍了Spring @Transactional注解失效解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 这几天在项目里面发现我使用@Transactional注解事务之后,抛了异常居然不回滚.后来终于找到了原因. 如果你也出现了这种情况,可以从下面开始排查. 一.特性 先来了解一下@Transactional注解事务的特性吧,可以更好排查问题 1.service类标签(一般不建议在接口上)上添加@Transactional,

  • Java设计模式之代理模式与@Async异步注解失效的解决

    目录 JDK动态代理实现自定义异步注解(@Async) SpringAOP实现自定义异步注解 Spring的异步注解@Async失效分析 自定义注解实现方式 JDK动态代理实现自定义异步注解(@Async) 实现思路: 首先自定义一个注解,命名为:ExtAsync 实现一个接口,这个接口的实现类就是被代理类 实现jdk的InvocationHandler接口,根据反射获取目标方法的信息,判断是否有异步注解,如果有则另起一个线程异步执行去. 1.异步注解 @Target({ElementType.

  • Spring AOP注解失效的坑及JDK动态代理

    @Transactional @Async等注解不起作用 之前很多人在使用Spring中的@Transactional, @Async等注解时,都多少碰到过注解不起作用的情况. 为什么会出现这些情况呢?因为这些注解的功能实际上都是Spring AOP实现的,而其实现原理是通过代理实现的. JDK动态代理 以一个简单的例子理解一下JDK动态代理的基本原理: //目标类接口 public interface JDKProxyTestService { void run(); } //目标类 publ

  • 重新启动IDEA时maven项目SSM框架文件变色所有@注解失效

    重新启动IDEA maven项目SSM框架所有@注解失效,每个文件上都有个小黄圆,而且我发现所有构建项目的maven的jar包都不在了,也就是说此时根本就不是一个maven项目了,这是IDEA的一个很烦人的bug,网上有很多解决的办法,我是这样解决的: Build -> Rebuild Project 将项目进行重构 此时你会发现maven jar包重新导入进来 而文件异常是因为之前的文件标记消失了,重新标记 因为我这是SSM框架所以三个文件夹需要标记 右键各个文件 Mark Directory

  • 解决SpringBoot中使用@Async注解失效的问题

    错误示例,同一个类中使用异步方法: package com.xqnode.learning.controller; import com.fasterxml.jackson.core.JsonProcessingException; import org.springframework.scheduling.annotation.Async; import org.springframework.web.bind.annotation.GetMapping; import org.springf

  • javax NotBlank和Email注解失效的解决

    javax NotBlank和Email注解失效 使用javax的NotBlan和Email注解, 结果报类似错误 no validator could be found for constraint 'javax.validation.constraints.notblank' 原来是由于javax只提供了注解的定义,未提供对应的处理器,一般使用hibernate提供的注解处理器. 但是hibernate未提供NotBlank和Email注解的处理器(但是hibernate自己定义的NotBl

  • @Transaction,@Async在同一个类中注解失效的原因分析及解决

    目录 @Transaction @Async在同一个类中注解失效 下面用伪代码阐述一下原因 说说解决 @Async的实现类方式 方法1:实现接口AsyncConfigurer 方法2:直接注入bean @Transaction @Async在同一个类中注解失效 在同一个类中,一个方法调用另外一个有注解(比如@Async,@Transational)的方法,注解是不会生效的. 比如,下面代码例子中,有两方法,一个有@Async注解,一个没有.第一次如果调用了有注解的test()方法,会启动@Asy

随机推荐