SpringCache–同类方法互相调用导致缓存失效的解决方案
1. 还原案发现场
同一个类下,存在两个方法:methodA和methodB,其中methodA增加@Cacheable注解,methodB方法内调用methodA,会发现methodA的缓存失效。如下:
@Slf4j
@Service
public class TestService{
@Cacheable(value = "test", key = "targetClass + methodName")
public String methodA() {
log.info("进入函数了");
return "methodA";
}
public String methodB() {
return methodA();
}
}
当外界调用methodA时,第一次调用会执行log.info(“进入函数了”);,之后再调用methodA后,就不会再执行了,证明缓存已经生效。
而当外界调用methodB时,无论调用几次,都会执行log.info(“进入函数了”);,缓存就这么失效了。至于为什么会失效,请自行百度,这里不再赘述,只介绍如何用最简单的方式解决。
2. 两步就破案了?!
有两个方法可以解决缓存失效的方法,一种就是自己再创建一个类去调用methodA,这样可以保证每次methodA的缓存可以生效,但是要额外增加一个类,本人确实不喜欢如此繁琐的方法。
@Slf4j
@Service
public class TestService2{
public String methodB() {
TestService testService = new TestService();
return testService.methodA();
}
}
看到这里说明你不喜欢繁琐的方法,那就和我用一句话解决此问题,不多增加任何一个类,优雅解决此问题
@Slf4j
@Service
public class TestService{
//此处为增加的关键语句
@Autowired
private TestService testService ;
@Cacheable(value = "test", key = "targetClass + methodName")
public String methodA() {
log.info("进入函数了");
return "methodA";
}
public String methodB() {
//这个地方也要注意了,要用testService去调用methodA
return testService.methodA();
}
}
如此之后便解决了同类方法互相调用导致缓存失效的问题。