小编典典

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

spring-boot

我有如下方法:

@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
}

我在其中一个配置类中启用了缓存:

@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();
    }

}

我的内容如下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>

我声明CacheManager如下:

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

当我将一个@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(第二次来自缓存),它也应该打印一次。但是它打印两次。


阅读 1236

收藏
2020-05-30

共1个答案

小编典典

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

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

2020-05-30