@Cacheable 不拦截方法,缓存始终为空

Has*_*ral 5 java spring caching spring-boot spring-cache

我有一个方法如下:

@Cacheable(value = "SAMPLE")
public List<SomeObj> find() {
     // Method that initiates and returns the List<SomeObj> and takes around 2-3 seconds, does some logging too
}
Run Code Online (Sandbox Code Playgroud)

我正在我的配置类之一中启用缓存:

@EnableCaching
@Configuration
public SomeConf extends CachingConfigurerSupport {

    // Here I also initialize my classes with @Cacheable annotation

    @Bean
    @Override
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        cacheManager.setCaches(Collections.singletonList((new ConcurrentMapCache("SAMPLE"))));
        return cacheManager;
    }


    @Bean
    @Override
    public CacheResolver cacheResolver() {
        return new SimpleCacheResolver(cacheManager());
    }

    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return new SimpleKeyGenerator();
    }

}
Run Code Online (Sandbox Code Playgroud)

我的 中有以下内容pom.xml

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
    <version>1.5.14.RELEASE</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

我声明CacheManager如下:

@Bean
public CacheManager cacheManager(){
    SimpleCacheManager cacheManager = new SimpleCacheManager();
    cacheManager.setCaches(Collections.singletonList((new ConcurrentMapCache("SAMPLE"))));
    return cacheManager;
}
Run Code Online (Sandbox Code Playgroud)

当我将一个@Autowired CacheManager实例放入其中一个@Service实例时,我可以看到存在一个名为 name 的缓存"SAMPLE",但其条目始终为空。我一次又一次地调用该方法find(),但它似乎没有填充缓存。

我尝试int a向该find()方法添加一个参数(例如 )并将其作为key = "#a"@Cacheable但没有任何改变。

当我尝试在隔离环境中重现问题时,我可以看到它工作正常。但是,当我添加依赖项(非开源公司库,EhCache也包括配置)时,它不起作用。我该如何调试这个,我做错了什么?

更新:

我也尝试过cacheManager = myCacheManager使用@Cacheable。没有运气。

更新2:

我正在使用AspectJSpring AOP。我想可能跟它也有关系。我尝试过@EnableCaching(mode = AdviceMode.ASPECTJ)@EnableLoadTimeWeaving同样的事情。

更新3:

我终于能够重现这个问题,这里是:client-api-cache

基本上,当您运行应用程序telnet localhost 9000并向其发送任何行后,NOT CACHED即使该方法被调用两次CachedController(第二次来自缓存),它也应该打印一次。但它打印了两次。

小智 4

根本原因是您滥用了“afterPropertiesSet”。因此,您所做的是无限循环,并且永远不会将控制权传递回 Spring 管道,因此 Spring 无法正确初始化缓存设施。

查看解决我们问题的代码:https ://dumpz.org/cbx8h28KeAss