java - spring - 使用谷歌 Guava 缓存

标签 java spring caching google-guava-cache

我正在尝试在我的 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/

相关文章:

angularjs - $cacheFactory 在页面重新加载时删除我的缓存

java - 根据其他属性值在 Maven 中定义属性

Java - (android) 在刷新其 OutputStream 后重用一个进程

java - 查明 BufferedImage 是否被点击

spring - 在 spring bean 定义之外的 spring bean 中设置属性

java - 如何在 Spring Boot 中的组件中 Autowiring 存储库接口(interface)

spring - Session 空指针异常

java - 循环遍历字节数组中的十六进制数字

caching - Clojure 的lazy-seq 缓存

asp.net-mvc - ASP.NET MVC 响应过滤器 + OutputCache 属性