spring - 使用 google 番石榴缓存
spring - using google guava cache
我正在尝试在我的 spring 应用程序中使用 google 番石榴缓存,但结果永远不会缓存。
这是我的步骤:
在配置文件中:
@EnableCaching
@Configuration
public class myConfiguration {
@Bean(name = "CacheManager")
public CacheManager cacheManager() {
return new GuavaCacheManager("MyCache");
}
}
在class我想使用缓存:
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");
}
我正在尝试在我的 spring 应用程序中使用 google 番石榴缓存,但结果永远不会缓存。
这是我的步骤:
在配置文件中:
@EnableCaching
@Configuration
public class myConfiguration {
@Bean(name = "CacheManager")
public CacheManager cacheManager() {
return new GuavaCacheManager("MyCache");
}
}
在class我想使用缓存:
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");
}