Redis를 캐싱서버로 사용하는 방법에 대해 정리해 보고자 한다.
Redis 개념과 기본 설정에 대해서는 아래 포스팅을 참고하기 바란다.
- SpringBoot Redis 설정 및 Example
@Configuration
@RequiredArgsConstructor
@EnableCaching
@EnableRedisRepositories
public class RedisConfiguration {
@Value("${spring.redis.host}")
private String redisHost;
@Value("${spring.redis.port}")
private int redisPort;
@Bean
public RedisConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory(redisHost, redisPort);
}
@Bean
public RedisCacheManager redisCacheManager() {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(30))
.disableCachingNullValues()
.serializeKeysWith(RedisSerializationContext.SerializationPair
.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair
.fromSerializer(new GenericJackson2JsonRedisSerializer()))
;
Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
redisCacheConfigurationMap.put("holiday", redisCacheConfiguration.entryTtl(Duration.ofHours(1)));
redisCacheConfigurationMap.put("trade", redisCacheConfiguration.entryTtl(Duration.ofMinutes(10)));
return RedisCacheManager.RedisCacheManagerBuilder
.fromConnectionFactory(redisConnectionFactory())
.cacheDefaults(redisCacheConfiguration)
.withInitialCacheConfigurations(redisCacheConfigurationMap)
.build();
}
}
캐시마다 서로 다른 설정을 적용하고 싶다면 RedisCacheManager의 withInitialCacheConfigurations메서드를 통해 개별 캐시 설정을 할 수 있다.
메서드의 결과를 캐시에 저장하고, 같은 입력으로 메서드를 호출할 때 캐시된 값을 반환한다.
메서드 실행 후 캐시에 값을 업데이트한다.
캐시에 저장된 값을 삭제한다.
속성 | 설명 | Ex | 어노테이션 |
value | 캐시의 이름을 지정 | @Cacheable(value = "holiday") | @Cacheable @CachePut @CacheEvict |
key | 캐시의 Key 지정 (SpEL 표현식) |
@Cacheable(value = "holiday", key = "#id") | @Cacheable @CachePut @CacheEvict |
cacheManager | 캐시 매니저를 지정 CacheManager 인터페이스를 구현한 빈을 사용하며, 애플리케이션에 여러 캐시 매니저가 있을 때 특정 매니저를 지정 |
@Cacheable(value = "holiday", key = "#id", cacheManager = "redisCacheManager") | @Cacheable @CachePut @CacheEvict |
condition | 캐싱 조건 정의 (SpEL 표현식) |
@Cacheable(value = "trade", condition = "#id > 10") | @Cacheable @CachePut @CacheEvict |
unless | 캐싱을 하지 않을 조건 정의 | @Cacheable(value = "trade", unless = "#result == null") | @Cacheable @CachePut |
sync | 여러 스레드에서 동시에 캐시를 접근할 때 메서드가 여러 번 실행되지 않도록 동기화 (Default : false) |
@Cacheable(value = "trade", sync = true) | @Cacheable |
allEntries | 전체 캐시 삭제 여부 특정 키가 아닌 캐시 전체를 비우고자 할 때 사용 (Default : false) |
@CacheEvict(value = "holiday", allEntries = true) | @CacheEvict |
beforeInvocation | 메소드 실행 전 캐시 삭제 여부 true : 메서드가 실행되기 전에 캐시가 무효화 false : 메서드가 성공적으로 실행된 후에 캐시가 무효화 (Default : false) |
@CacheEvict(value = "holiday", key = "#id", beforeInvocation = true) | @CacheEvict |
SpringBoot Redis 설정 및 Example (3) | 2024.09.02 |
---|
댓글 영역