SpringCache--同类方法互相调用导致缓存失效的解决方案

2022-07-01 14:25:50

SpringCache–同类方法互相调用导致缓存失效的解决方案

1. 还原案发现场

  同一个类下,存在两个方法:methodA和methodB,其中methodA增加@Cacheable注解,methodB方法内调用methodA,会发现methodA的缓存失效。如下:

@Slf4j@ServicepublicclassTestService{@Cacheable(value="test", key="targetClass + methodName")public StringmethodA(){
    	log.info("进入函数了");return"methodA";}public StringmethodB(){returnmethodA();}}

当外界调用methodA时,第一次调用会执行log.info(“进入函数了”);,之后再调用methodA后,就不会再执行了,证明缓存已经生效。
而当外界调用methodB时,无论调用几次,都会执行log.info(“进入函数了”);,缓存就这么失效了。至于为什么会失效,请自行百度,这里不再赘述,只介绍如何用最简单的方式解决。

2. 两步就破案了?!

  有两个方法可以解决缓存失效的方法,一种就是自己再创建一个类去调用methodA,这样可以保证每次methodA的缓存可以生效,但是要额外增加一个类,本人确实不喜欢如此繁琐的方法。

@Slf4j@ServicepublicclassTestService2{public StringmethodB(){
        TestService testService=newTestService();return testService.methodA();}}

  看到这里说明你不喜欢繁琐的方法,那就和我用一句话解决此问题,不多增加任何一个类,优雅解决此问题

@Slf4j@ServicepublicclassTestService{//此处为增加的关键语句@Autowiredprivate TestService testService;@Cacheable(value="test", key="targetClass + methodName")public StringmethodA(){
    	log.info("进入函数了");return"methodA";}public StringmethodB(){//这个地方也要注意了,要用testService去调用methodAreturn testService.methodA();}}

如此之后便解决了同类方法互相调用导致缓存失效的问题。

  • 作者:凉凉在上
  • 原文链接:https://blog.csdn.net/cheng137666/article/details/110189594
    更新时间:2022-07-01 14:25:50