스프링 - Redis CacheManager ClassCastException 해결하기

2024. 12. 7. 23:11· Spring
목차
  1. Cacheable 어노테이션
  2. 해결 방법
  3. 1. 의존성에서 Spring Boot DevTools를 제거하는 방법
  4. 2. RedisConfig에서 cacheManager를 정의할 때 클래스 로더를 명시적으로 지정하는 방법

스프링 - Redis CacheManager ClassCastException 해결하기

 

작성 일자 : 2024년 12월 07일


 

ClassCastException illustrated by Dalle3

 

 

Cacheable 어노테이션

 

스프링에서는 @Cacheable 어노테이션을 사용하여 아래의 예시와 같이 메서드의 리턴 값을 캐싱할 수 있습니다.

@Cacheable(value = "latest-post", key = "#root.methodName")
public List<Post> getLatestPosts() {
    List<Post> posts = postRepository.findAllByOrderByCreatedAtDesc();
    return posts;
}

 

Redis를 캐시 스토어로 사용할 때, cacheName이 latest-post인 캐시 하나만 사용하는 경우에는 문제가 발생하지 않지만, 여러 개의 캐시를 사용하는 경우에 갑자기 아래와 같은 ClassCastException가 발생하였습니다.

java.lang.ClassCastException: class com.github.gerrymandering.domain.post.controller.response.GetPostRankingResponseDto cannot be cast to class com.github.gerrymandering.domain.post.controller.response.GetPostRankingResponseDto

 


 

해결 방법

 

1. 의존성에서 Spring Boot DevTools를 제거하는 방법

 

build.gradle 파일에서 spring-boot-devtools 의존성을 제거합니다.

 


 

2. RedisConfig에서 cacheManager를 정의할 때 클래스 로더를 명시적으로 지정하는 방법

 

@Configuration
@EnableCaching
@RequiredArgsConstructor
public class RedisConfig {

    private final ResourceLoader resourceLoader;

    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheConfiguration config = RedisCacheConfiguration
                .defaultCacheConfig(resourceLoader.getClassLoader())
                .entryTtl(Duration.ofHours(1));

        return RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(config)
                .withCacheConfiguration("latest-post",
                        RedisCacheConfiguration
                                .defaultCacheConfig(resourceLoader.getClassLoader())
                                .entryTtl(Duration.ofMinutes(10)))
                .withCacheConfiguration("ranking",
                        RedisCacheConfiguration
                                .defaultCacheConfig(resourceLoader.getClassLoader())
                                .entryTtl(Duration.ofHours(2)))
                .build();
    }
}

 

  • 위와 같이 RedisCacheConfiguration을 생성할 때, 역 직렬화에 사용할 클래스 로더를 resourceLoader.getClassLoader()로 지정해줍니다.

 

Reference

https://brunch.co.kr/@springboot/212

 

Spring Boot DevTools 클래스로더 이슈

- 스프링부트 관련 잡다한 기술 이야기 | "Spring Boot DevTools 클래스로더 이슈"라는 제목으로 글을 작성하였는데, 막상 글을 다 작성한 후 다시 읽어보니 너무 잡다한 내용이 되었다. 그래서, 이 글

brunch.co.kr

https://myclude.tistory.com/entry/javalangClassCastException-class-%E2%80%A6-is-in-unnamed-module-of-loader-app-spring-boot-dev-tools

 

java.lang.ClassCastException: class … is in unnamed module of loader 'app' - spring-boot-dev-tools

쿼츠 개발 시 다음과 같은 오류를 보게 되었다. org.quartz.SchedulerException: TriggerListener 'SimpleTriggerListener' threw exception: class me.myclude.quartz.info.TimerInfo cannot be cast to class me.myclude.quartz.info.TimerInfo (me.myclu

myclude.tistory.com

https://12hong.tistory.com/23

 

같은 클래스인데 왜 ClassCastException이 발생하는걸까? Redis Cache Manager가 DevTools와 만났을 때

캐싱 했더니 ClassCastException이 발생한다. java.lang.ClassCastException: com.example.demo.User cannot be cast to com.example.demo.User ?????????????? 이해할 수 없는 에러 메시지였다. 앞뒤가 똑같은 클래스구만 왜 캐스팅

12hong.tistory.com

https://medium.com/javarevisited/classcast-exception-when-using-redis-and-springboot-frameworks-in-conjunction-ea132dd0d7ea

 

ClassCast Exception when using Redis and Springboot frameworks in conjunction

Frameworks undoubtedly make things a lot easier for developer’s as they enables us to focus on the business aspect of the application.

medium.com

 

저작자표시 (새창열림)
  1. Cacheable 어노테이션
  2. 해결 방법
  3. 1. 의존성에서 Spring Boot DevTools를 제거하는 방법
  4. 2. RedisConfig에서 cacheManager를 정의할 때 클래스 로더를 명시적으로 지정하는 방법
'Spring' 카테고리의 다른 글
  • 스프링 - RabbutMQ Retry 정책 설정하기(ft. 10만원의 교훈)
  • 스프링 - Redission 분산락으로 동시성 문제 해결하기 예시
  • 스프링 - LLM Response를 Redis Streams와 SSE로 스트리밍 해보자
  • 스프링 RabbitMQ 연동하기
gerrymandering
gerrymandering
gerrymandering
gerrymandering
gerrymandering
전체
오늘
어제
  • 분류 전체보기 (83)
    • SOLID 원칙 (6)
    • 번역 (4)
    • Nginx (1)
    • Tailwind CSS (1)
    • AWS (7)
      • DMS를 사용한 RDS to OpenSearch .. (3)
      • ECS를 이용한 Blue-Green 무중단 배포 .. (7)
    • NextJS (7)
    • 기타 (12)
    • Prompt Engineering (6)
    • 읽어볼만한 글 (3)
      • 기술 (0)
      • 쓸만한 툴 (0)
      • 아이템 (0)
      • 웹 디자인 (0)
      • 기타 (3)
    • Cloud Architecture (4)
    • Trouble Shooting (9)
    • Spring (11)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

최근 댓글

최근 글

글쓰기 / 관리자
hELLO · Designed By 정상우.v4.2.1
gerrymandering
스프링 - Redis CacheManager ClassCastException 해결하기
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.