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

2023-12-21

我有一个方法如下:

@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我可以看到存在一个名为"SAMPLE",但其条目始终为空。我一次又一次地调用这个方法find(),但它似乎没有填充缓存。

我试图提出一个论点(比如说int a)到find()方法并将其表示为key = "#a" to @Cacheable,但没有任何改变。

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

Update:

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

更新2:

我在用AspectJ和 Spring AOP。我想可能跟它也有关系。我努力了@EnableCaching(mode = AdviceMode.ASPECTJ) with @EnableLoadTimeWeaving但同样的事情。

更新3:

我终于能够重现这个问题,如下:客户端 api 缓存 https://github.com/hasancansaral/client-api-cache

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


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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

@Cacheable 不拦截方法,缓存始终为空 的相关文章

随机推荐