Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Config Spring cache using Guava

Following the spring documentation about cache I could use cache on my project, but how can I configure guava to define a expired time or size per cache name?

applicationConfig.xml

<bean id="cacheManager" class="org.springframework.cache.guava.GuavaCacheManager"/>

Foo.java

@Cacheable(value="courses", key="#user.id")
public List<Course> getCoursesByUser(User user) {
    ...
}
like image 770
xedo Avatar asked Feb 03 '15 10:02

xedo


2 Answers

You can configure caches separately. See Spring Guava cache

@Bean
public CacheManager cacheManager() {
    SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
    GuavaCache bookCache = new GuavaCache("book", CacheBuilder.newBuilder().build());
    GuavaCache booksExpirableCache = new GuavaCache("books", CacheBuilder.newBuilder()
            .expireAfterAccess(30, TimeUnit.MINUTES)
            .build());
    simpleCacheManager.setCaches(Arrays.asList(bookCache, booksExpirableCache));
    return simpleCacheManager;
}
like image 112
Kyrylo Semenko Avatar answered Oct 10 '22 22:10

Kyrylo Semenko


You can specify CacheBuilder for your GuavaCacheManager in your Spring configuration

  1. In case of Java configuration it can look like this:
@Bean
public CacheManager cacheManager() {
    GuavaCacheManager cacheManager = new GuavaCacheManager();
    cacheManager.setCacheBuilder(
        CacheBuilder.
        newBuilder().
        expireAfterWrite(2, TimeUnit.SECONDS).
        maximumSize(100));
    return cacheManager;
}
  1. In case of XML configuration, you can use CacheBuilderSpec in guava
<bean id="legendaryCacheBuilder"
      class="com.google.common.cache.CacheBuilder"
      factory-method="from">
    <constructor-arg value="maximumSize=42,expireAfterAccess=10m,expireAfterWrite=1h" />
</bean>

For more information look at:

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/cache/CacheBuilderSpec.html

Injecting Google guava cache builder into bean via Spring

like image 27
mavarazy Avatar answered Oct 10 '22 23:10

mavarazy