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
build.gradle
implementation 'org.springframework.boot:spring-boot-starter-cache'
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
@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.
@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";
}
}
Access the following and the cache will be created in Redis http://localhost:8080/api/sample/redisCache
Redis expiration date is according to the setting class
It's been a while before the TTL is issued.
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