我正在尝试在我的 spring 应用程序中使用 google guava 缓存,但结果永远不会缓存。
这是我的步骤:
在配置文件中:
@EnableCaching
@Configuration
public class myConfiguration {
@Bean(name = "CacheManager")
public CacheManager cacheManager() {
return new GuavaCacheManager("MyCache");
}
}
在类里面我想使用缓存:
public class MyClass extends MyBaseClass {
@Cacheable(value = "MyCache")
public Integer get(String key) {
System.out.println("cache not working");
return 1;
}
}
然后当我打电话时:
MyClass m = new MyClass();
m.get("testKey");
m.get("testKey");
m.get("testKey");
每次都是进入函数,不使用缓存: 控制台:
cache not working
cache not working
cache not working
有人知道我遗漏了什么或者我该如何调试吗?
最佳答案
你不应该自己管理一个spring bean。让 spring 来管理它。
@EnableCaching
@Configuration
public class myConfiguration {
@Bean(name = "CacheManager")
public CacheManager cacheManager() {
return new GuavaCacheManager("MyCache");
}
@Bean
public MyClass myClass(){
return new MyClass();
}
}
之后,您应该以托管方式使用 MyClass。
public static void main(String[] args) throws Exception {
final ApplicationContext applicationContext = new AnnotationConfigApplicationContext(myConfiguration.class);
final MyClass myclass = applicationContext.getBean("myClass");
myclass.get("testKey");
myclass.get("testKey");
myclass.get("testKey");
}
关于java - spring - 使用谷歌 Guava 缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32093019/