Total Pageviews

2016/06/04

[Spring Framework] Caching in Spring (Using GuavaCache)

Problem
I'm using default cache in Spring framework. 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.xxx.cache;

import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;

// http://www.baeldung.com/spring-cache-tutorial
/*
 * To enable caching, Spring makes good use of annotations, much like enabling any other
 * configuration level feature in the framework.
 * 
 * The caching feature can be declaratively enabled by simply adding the @EnableCaching annotation
 * to any of the configuration classes:
 */
@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public CacheManager cacheManager() {
        String cacheNames[] = new String[] { "comConfig" };
        // Construct a static ConcurrentMapCacheManager, managing caches for the specified cache
        // names only.
        return new ConcurrentMapCacheManager(cacheNames);
    }

}

If I would like to set the TTL of chache (ex. 1 minute), how to do it?


How-to
Here is the sample code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.xxx.cache;

import java.util.concurrent.TimeUnit;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.guava.GuavaCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.google.common.cache.CacheBuilder;
import com.google.common.collect.ImmutableList;

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public CacheManager cacheManager() {
        // instantiate GuavaCacheManager
        GuavaCacheManager cacheManager = new GuavaCacheManager();
  
        // set expire time to 1 minute
        cacheManager.setCacheBuilder(CacheBuilder.newBuilder().expireAfterAccess(1,
                TimeUnit.MINUTES));
        
        // set cache name    
        cacheManager.setCacheNames(ImmutableList.of("comConfig"));

        return cacheManager;
    }
}


Reference
[1] https://dzone.com/articles/spring-caching-abstraction-and

No comments: