spring - using google guava cache

2019-05-15 06:34发布

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

This are my steps:

in conf file:

@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;
    }
}

Then when I'm calling:

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?

1条回答
霸刀☆藐视天下
2楼-- · 2019-05-15 07:05

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

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");
}
查看更多
登录 后发表回答