본문 바로가기

Programming!

Redis(Lettuce) 캐시 적용시 expire time(ttl) 지정

@Cacheable에는 왜 expires 속성이 없는 것일까..를 늘~ 고민하면서.

 

기존에는 이렇게 CacheManager를 따로 생성하는 코드를 만들거나 보았더랬다..

@Bean("이건10분짜리야")
public CacheManager redisCacheManager10() {
...
}

@Bean("이건60분짜리야")
public CacheManager redisCacheManager60() {
...
}

참 이상도 하지.. 그냥 기존에 저런 코드가 있으면 다음에 100분짜리가 생겨야 하면 그냥 C&P를 해버린다..읔..

 

이번에는 좀 바꾸어 보았다.  CacheConfigurationProperties에 cache key와 value(ttl)를 Map으로 지정해 준다.

// DEV profiles
public class LettuceRedisCacheConfiguration extends CachingConfigurerSupport {

....

	@Bean
	public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory, CacheConfigurationProperties properties) {
		Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();
		for (Entry<String, Long> cacheNameAndTimeout : properties.getCacheExpirations().entrySet()) {
			log.info("CacheManager CacheValue{} = CacheTtl{}", cacheNameAndTimeout.getKey(), cacheNameAndTimeout.getValue());
			cacheConfigurations.put(cacheNameAndTimeout.getKey(), createCacheConfiguration(cacheNameAndTimeout.getValue()));
		}
		return RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(cacheConfiguration(properties))
				.withInitialCacheConfigurations(cacheConfigurations).build();
	}
....

}

CacheManager 지정시 캐시 설정을 추가해 봄.

@Cacheable(value = "banner", key = "#id")
public Banner findById(Long id){
....

우선 잘 됨. 물론 테스트 해봐야 함.

 

그외 참고 :

https://shekhargulati.com/2018/07/11/configuring-spring-cache-manager-with-aws-elasticcache-redis-cluster-mode-disabled-and-lettuce/

 

Configuring Spring Cache Manager with AWS ElastiCache Redis (cluster mode disabled) and Lettuce

We have Spring Boot 2 application that uses Redis as the cache manager. We deploy our application on Amazon AWS where we use AWS ElastiCache Redis service in cluster mode disabled. Our setup includ…

shekhargulati.com

https://github.com/Grokzen/docker-redis-cluster

 

Grokzen/docker-redis-cluster

Dockerfile for Redis Cluster (redis 3.0+). Contribute to Grokzen/docker-redis-cluster development by creating an account on GitHub.

github.com