개발/java

[spring] 캐치 추가/제거 Annotation : @Cacheable, @CacheEvict + Redis 캐시 설정방법

ttoance 2025. 3. 12. 12:53
반응형

선언형 애노테이션 기반 캐싱 (Declarative Annotation-based Caching)

Spring의 캐싱 추상화(Spring’s caching abstraction)는 캐싱을 선언하기 위한 여러 개의 Java 애노테이션을 제공함.

  • @Cacheable: 캐시를 채우는 동작을 트리거함. (해당 메서드의 반환 값을 캐시에 저장)
 @Cacheable(key = "#studyGroupId" ,value = STUDYGROUP_LIST, cacheManager = "redisCacheManager")
    @Transactional(readOnly = true)
    @Override
    public StudyGroupResponse getById(Long studyGroupId) {

        StudyGroup studyGroup = studyGroupRepository.findById(studyGroupId)
                .orElseThrow(() -> {
                    log.error("studyGroup 대상이 없습니다. studyGroupId: {}", studyGroupId);
                    throw new WSApiException(ErrorCode.NO_FOUND_ENTITY, "can't find a StudyGroup by " +
                            " studyGroupId: " + studyGroupId);
                });

        return mapToDto(studyGroup);
    }
  • @CacheEvict: 캐시에서 특정 데이터를 제거하는 동작을 트리거함.
    @CacheEvict(key = "#studyGroupId", value = STUDYGROUP_LIST, cacheManager = "redisCacheManager")
    @Transactional
    @Override
    public void deleteById(Long studyGroupId) {
        studyGroupRepository.deleteById(studyGroupId);
    }
  • @CachePut: 메서드 실행 결과를 캐시에 반영하지만, 메서드 실행을 방해하지 않음.
  • @Caching: 여러 개의 캐시 작업을 하나의 메서드에 적용할 수 있도록 그룹화함.
  • @CacheConfig: 클래스 레벨에서 공통 캐시 설정을 공유하도록 함.

 
 

Redis 캐시 (Redis Cache)

Spring Data Redis는 org.springframework.data.redis.cache 패키지에서 Spring 프레임워크의 캐시 추상화(Cache Abstraction) 구현을 제공함.
Redis를 캐시 저장소로 사용하려면 RedisCacheManager를 구성에 추가해야 함.

@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
    return RedisCacheManager.create(connectionFactory);
}

 
위의 예제에서 볼 수 있듯이, RedisCacheManager는 개별 캐시에 대한 맞춤 설정을 허용함.
RedisCacheManager가 생성하는 RedisCache의 동작은 RedisCacheConfiguration을 통해 정의됨. 이 설정을 사용하면 키 만료 시간, 접두사(prefix), 그리고 바이너리 저장 형식으로 변환하는 RedisSerializer 구현을 지정할 수 있음. 아래 예제와 같이 설정할 수 있음.

RedisCacheManager cacheManager = RedisCacheManager.builder(connectionFactory)
    .cacheDefaults(RedisCacheConfiguration.defaultCacheConfig())
    .transactionAware()
    .withInitialCacheConfigurations(Collections.singletonMap("predefined",
        RedisCacheConfiguration.defaultCacheConfig().disableCachingNullValues()))
    .build();

 
 
https://docs.spring.io/spring-framework/reference/integration/cache/annotations.html

Declarative Annotation-based Caching :: Spring Framework

The caching abstraction lets you use your own annotations to identify what method triggers cache population or eviction. This is quite handy as a template mechanism, as it eliminates the need to duplicate cache annotation declarations, which is especially

docs.spring.io

https://docs.spring.io/spring-data/redis/reference/redis/redis-cache.htm

Redis Cache :: Spring Data Redis

In order to achieve true time-to-idle (TTI) expiration-like behavior in your Spring Data Redis application, then an entry must be consistently accessed with (TTL) expiration on every read or write operation. There are no exceptions to this rule. If you are

docs.spring.io

https://velog.io/@mooh2jj/Redis-Cacheable-CacheEvict

[SpringBoot] 조회 API Redis 캐싱적용 @Cacheable, @CacheEvict

Redis @Cacheable, @CacheEvict 개념을 정리해봅니다.1) @Cacheable: 데이터를 조회할 때, 레디스 캐싱 처리2) @CacheEvict: value or cacheNames 으로 지정된 레디스 캐시 제거

velog.io

 

반응형