春天-使用谷歌番石榴缓存 [英] spring - using google guava cache

查看:126
本文介绍了春天-使用谷歌番石榴缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的spring应用程序中使用google guava缓存,但是结果永远不会缓存。

I'm trying to use google guava cache in my spring app, but result is never caching.

这是我的步骤:

在conf文件中:

@EnableCaching
@Configuration
public class myConfiguration {
        @Bean(name = "CacheManager")
        public CacheManager cacheManager() {
            return new GuavaCacheManager("MyCache");
        }
}

在课堂上我想使用缓存:

In class I want to use caching:

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");

每次都在输入功能,而不使用缓存:
控制台:

It's entering function each time and not using cache: console:

 cache not working
 cache not working 
 cache not working

有人知道我丢失了什么,或者如何调试?

Does someone have an idea what am I missing or how can I debug that?

推荐答案

您不应该自己管理spring bean。让春天来管理它。

You should not manage a spring bean by yourself. Let spring to manage it.

@EnableCaching
@Configuration
public class myConfiguration {
        @Bean(name = "CacheManager")
        public CacheManager cacheManager() {
            return new GuavaCacheManager("MyCache");
        }

        @Bean
        public MyClass myClass(){
            return new MyClass();
        }
}

之后,您应该以托管方式使用MyClass。

After that you should use MyClass in a managed manner.

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");
}

这篇关于春天-使用谷歌番石榴缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆