【发布时间】:2018-09-26 12:57:52
【问题描述】:
我有一个方法如下:
@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;
}
当我将@AutowiredCacheManager 实例放入我的@Services 之一时,我可以看到存在一个名为"SAMPLE" 的缓存,但其条目始终为空。我一遍又一遍地调用方法find(),但它似乎没有填充缓存。
我尝试将参数(例如 int a)放入 find() 方法并将其作为 key = "#a" 放入 @Cacheable,但没有任何改变。
当我尝试在隔离环境中重现问题时,我可以看到它可以正常工作。但是当我添加我的依赖项(非开源公司库,其中也包括EhCache 配置)时,它不起作用。我该如何调试,我做错了什么?
更新:
我也尝试在@Cacheable 中使用cacheManager = myCacheManager。没有运气。
更新 2:
我正在使用AspectJ 和 Spring AOP。我认为这可能与它有关。我试过 @EnableCaching(mode = AdviceMode.ASPECTJ) 和 @EnableLoadTimeWeaving 但同样的事情。
更新 3:
我终于能够重现这个问题,这里是:client-api-cache
基本上,当您运行应用程序和telnet localhost 9000 发送任何行后,它应该打印一次NOT CACHED,即使该方法在CachedController 中调用了两次(第二次来自缓存)。但它会打印两次。
【问题讨论】:
-
类路径中是否有定义名为“find():List
”的缓存的 ehcache.xml 文件? -
感谢您的评论。这里有两种情况:1)我没有显式配置一个
CacheManager,而Spring配置了一个GuavaCacheManager,所以ehcache.xml是无关紧要的。 2)当我用EhCacheManager明确定义CacheManager@Bean并放置一个定义名为“find():List”的缓存的ehcache.xml(实际上它不接受 <字符所以我不得不替换缓存名称但仍然)。在这两种情况下,都无法正常工作。 -
@AndrewS 对于更新后的问题,您还能想到什么吗?谢谢。
-
你能确认
SomeConf被扫描了吗?find()没有参数,所以不确定它会使用什么作为键 - 也许获取 Spring 源代码以查看缓存代理类是否实际被调用。 -
@AndrewS 我可以确认
@SomeConf已被扫描。我还尝试将参数(int a)放入find()方法并将其作为key = "#a"放入@Cacheable,但没有任何改变。
标签: java spring spring-boot caching spring-cache