在同一个Bean中调用@Cacheable方法
Spring提供了一种基于注解的方法来启用Spring管理Bean的缓存。基于AOP技术,通过在方法上添加@Cacheable注解,可以很容易地使方法可缓存。然而,当从同一个类内部调用时,缓存将被忽略。
在本教程中,我们将解释为什么会发生这种情况以及如何解决它。
2. 重现问题
首先,我们创建一个启用了缓存的Spring Boot应用程序。在本文中,我们创建了一个带有@Cacheable注解的square方法的MathService:
@Service
@CacheConfig(cacheNames = "square")
public class MathService {
private final AtomicInteger counter = new AtomicInteger();
@CacheEvict(allEntries = true)
public AtomicInteger resetCounter() {
counter.set(0);
return counter;
}
@Cacheable(key = "#n")
public double square(double n) {
counter.incrementAndGet();
return n * n;
}
}