스프링은 캐시 구현으로 레디스를 지원한다. 스프링 부트를 사용하면 다음의 간단한 설정만 추가하면 된다.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
진행중인 프로젝트에 캐시별 유효시간 설정 기능이 필요해서 스프링 부트로 다음과 같은 프로퍼티를 사용해서 캐시별로 유효 시간을 설정할 수 있도록 구현해봤다.
# application.properties
spring.cache.redis.defaultExpireTime=0
spring.cache.redis.expireTime.billDetailData=3600
spring.cache.redis.expireTime.billSummaryInfos=3600
이 설정에서 "spring.cache.redis"는 접두어이다. defaultExpireTime은 전체 캐시에 기본으로 적용할 유효시간을 설정한다. "expirTime.캐시이름"은 캐시 이름별로 캐시 시간을 설정한다. 유효 시간은 초 단위이다.
이 설정을 담기 위한 @ConfigurationProperties 클래스를 프로퍼티 클래스를 다음과 같이 작성했다.
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "spring.cache.redis")
public class CacheRedisProperties {
private long defaultExpireTime = 0L;
private Map<String, Long> expireTime = new HashMap<>();
private CacheTimeParser parser = new CacheTimeParser();
public long getDefaultExpireTime() {
return defaultExpireTime;
}
public void setDefaultExpireTime(long defaultExpireTime) {
this.defaultExpireTime = defaultExpireTime;
}
public Map<String, Long> getExpireTime() {
return expireTime;
}
public void setExpireTime(Map<String, Long> expireTime) {
this.expireTime = expireTime;
}
}
다음으로 RedisCacheManager에 유효 시간 설정하면 된다. 이를 위한 코드는 다음과 같다.
import java.util.Map.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheManagerCustomizer;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.cache.RedisCacheManager;
/**
* org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration 클래스 참고
*/
@Configuration
@EnableCaching
@EnableConfigurationProperties(CacheRedisProperties.class)
public class CustomRedisCacheConfiguration {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private CacheRedisProperties cacheRedisProperties;
@Bean
public CacheManagerCustomizer<RedisCacheManager> cacheManagerCustomizer() {
return new CacheManagerCustomizer<RedisCacheManager>() {
@Override
public void customize(RedisCacheManager cacheManager) {
cacheManager.setDefaultExpiration(cacheRedisProperties.getDefaultExpireTime());
cacheManager.setExpires(cacheRedisProperties.getExpireTime());
}
};
}
}
스프링부트가 제공하는 CacheManagerCustomizer를 이용하면 부트가 생성한 CacheManager를 커스터마이징할 수 있다. 이 기능을 사용해서 RedisCacheManager에 캐시 유효 시간을 설정하면 된다.