상세 컨텐츠

본문 제목

[SpringBoot, Redis] 캐시 설정 (@Cacheable, @CachePut, @CacheEvict)

Spring/Redis

by Chan.94 2024. 9. 5. 13:04

본문

반응형

Intro

Redis를 캐싱서버로 사용하는 방법에 대해 정리해 보고자 한다.

 

Redis 개념과 기본 설정에 대해서는 아래 포스팅을 참고하기 바란다.

 

- Redis 개념 및 특징, 메모리 정책

- SpringBoot Redis 설정 및 Example


RedisConfiguration.java

@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();
    }
}

@EnableCaching

  • Spring Boot 애플리케이션에서 캐싱을 활성화하는 데 사용.
  • 스프링 AOP기능을 활용해 메서드 호출 시 캐싱 동작을 인터셉트하고, 필요한 경우 캐시에서 값을 반환하거나 새로 캐시 하도록 동작
  • CacheManager를 자동으로 구성 (Default는 SimpleCacheManager)

RedisCacheConfiguration

  • entryTtl() : TTL(Time To Live) 설정
  • disableCachingNullValues() : 메서드 결과가 null인 경우 캐시에 저장하지 않도록 설정
  • serializeKeysWith() : 캐시 키 직렬화 방식 설정
  • serializeValuesWith() : 캐시 값 직렬화 방식 설정

캐시마다 서로 다른 설정을 적용하고 싶다면 RedisCacheManager의 withInitialCacheConfigurations메서드를 통해 개별 캐시 설정을 할 수 있다.


@Cacheable

메서드의 결과를 캐시에 저장하고, 같은 입력으로 메서드를 호출할 때 캐시된 값을 반환한다.

@CachePut

메서드 실행 후 캐시에 값을 업데이트한다.

@CacheEvict

캐시에 저장된 값을 삭제한다.

속성

속성 설명 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

 

반응형

'Spring > Redis' 카테고리의 다른 글

SpringBoot Redis 설정 및 Example  (3) 2024.09.02

관련글 더보기

댓글 영역

>