About specifying the validity period when saving the cache in Redis with Spring Cache

Background

I checked the validity period designation of Redis, but I created an article because the description was old and there was little information that can be used as it is * Surveyed as of 20200827

Confirm that Redis can specify the validity period for each data in Spring Cache

build.gradle

implementation 'org.springframework.boot:spring-boot-starter-cache'
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
Create configuration class
@Configuration
@EnableCaching
public class RedisConfig {

	@Bean
	public CacheManager cacheManager(RedisConnectionFactory fac) {
		
        //1. 1. Create cache from cache builder
		RedisCacheManagerBuilder builder = RedisCacheManager.builder(fac);
		builder
			.cacheDefaults(
		//2. Set default cache expiration
					RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofDays(1)))
		//3. 3. Set an expiration date for the cache named cache1
			.withCacheConfiguration("cache1", 
					RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(1)))
		//3. 3. Set an expiration date for the cache named cache2
			.withCacheConfiguration("cache2", 
					RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(1)));

		return builder.build();
	}
}

** Supplement **

1.

//fac is a RedisConnectionFactory type
RedisCacheManager rcm = RedisCacheManager.create(fac);

2.

3.

Controller for operation check (create cache1 and cache2)
@RestController
@RequestMapping("/api/sample")
public class SampleRedisCacheController {

	@Autowired
	CacheManager cm;

	@GetMapping("redisCache")
	public String redisCache() {

		Cache c1 = cm.getCache("cache1");
		c1.put("k1", 123456);
		c1.put("k2", 234567);

		Cache c2 = cm.getCache("cache2");
		c2.put("k1", 123456);
		c2.put("k2", 234567);

		return "redis cache test";
	}
}

Check result

comment

The contents of the CacheManager class seemed difficult, but I understood how to make it and various settings. The builder was mentioned in Effective Java. I feel that it was introduced because it is convenient to use when there are many arguments of the constructor. I think that it has been introduced because there are many setting values this time.

Recommended Posts

About specifying the validity period when saving the cache in Redis with Spring Cache
Precautions when specifying the URL in render
Null support cache in Spring Data Redis
About the mechanism when displaying the GUI with Docker
Use thymeleaf3 with parent without specifying spring-boot-starter-parent in Spring Boot
About the behavior when doing a file map with java
About specifying the JAXRS path
See the relative redirect behavior with the server.tomcat.use-relative-redirects setting in Spring Boot