Spring Boot cache via guava/caffeine

Keywords: Spring Google Java Ehcache

Spring Boot provides spring-boot-starter-cache, which supports multiple cache implementations, such as EHCache, Redis, GUAVA etc. Here we take lightweight GUAVA as an example:

I. Basic Use

0. First, you need to add dependencies. Versions are specified according to your needs.

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-cache</artifactId>
	<version>${v}</version>
</dependency>
<dependency>
	<groupId>com.google.guava</groupId>
	<artifactId>guava</artifactId>
	<version>${v}</version>
</dependency>

1. Open the cache and add @EnableCaching to the Application class

2. Use caching through @Cacheable

@Cacheable("{cacheNames}")
public Object needCache() {
	return ...;
}

 

2. Specifying Caching Policy

Spring boot provides application.xx-based configuration

spring.cache.type=GUAVA
spring.cache.cache-names=cacheName
# Refer to com.google.common.cache.CacheBuilderSpec for parameters
spring.cache.guava.spec=expireAfterWrite=7m

This configuration can only provide a policy cache (if there are multiple policy configurations directly based on configuration files, please leave a message), if different caching strategies need to be customized:

@Configuration
public class CacheConfig {

	/**
	 * Define cache strategy
	 * 
	 * @return CacheManager
	 */
	@Bean
	public CacheManager cacheManager() {
		SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
		List<Cache> caches = new ArrayList<>();

		# Failure after 5 minutes of caching
		caches.add(new GuavaCache("{cacheName}",
				CacheBuilder.newBuilder().expireAfterAccess(5, TimeUnit.MINUTES).build()));

		simpleCacheManager.setCaches(caches);

		return simpleCacheManager;
	}

}

 

Configuration completion discovery spring recommends caffeine instead of guava, so caffeine is used instead.

 

PS:  spring-gs-cachingcache-store-configuration-caffeineben-manes/caffeine

Posted by bubblocity on Wed, 13 Feb 2019 03:57:18 -0800