🚨 문제 상황
시험 타이머 기능 구현 중 Redis에 LocalDateTime을 저장하고 불러오는 과정에서 직렬화 관련 에러 발생
ClassCastException: class java.lang.String cannot be cast to class java.time.LocalDateTime
🔍 원인 분석
1. RedisTemplate의 기본 직렬화 동작
- ⚠️ RedisTemplate<String, Object>를 사용하여 Object 타입으로 LocalDateTime을 저장
- 📝 Redis는 데이터를 문자열로 저장하기 때문에 역직렬화 과정에서 타입 불일치 발생
- ❌ Jackson의 JavaTimeModule이 등록되어 있어도 Redis 저장/조회 시점에서는 적용되지 않음
2. 기존 코드의 문제점
@Service
public class ExamTimerService {
private final RedisTemplate<String, Object> redisTemplate;
public void startExamTimer(Long attemptId, Integer timeLimit) {
LocalDateTime endTime = LocalDateTime.now().plusMinutes(timeLimit);
redisTemplate.opsForValue().set(key, endTime, timeLimit, TimeUnit.MINUTES);
}
}
✨ 해결 방법
1. RedisTemplate 타입 변경
- 🔄 Object 대신 String 타입 사용
- 📋 LocalDateTime을 명시적으로 String으로 변환하여 저장
2. 수정된 코드
@Service
public class ExamTimerService {
private final RedisTemplate<String, String> redisTemplate;
public void startExamTimer(Long attemptId, Integer timeLimit) {
LocalDateTime endTime = LocalDateTime.now().plusMinutes(timeLimit);
redisTemplate.opsForValue().set(key, endTime.toString(), timeLimit, TimeUnit.MINUTES);
}
public Long getRemainingTime(Long attemptId) {
String endTimeStr = redisTemplate.opsForValue().get(key);
if (endTimeStr == null) {
return 0L;
}
LocalDateTime endTime = LocalDateTime.parse(endTimeStr);
return ChronoUnit.SECONDS.between(LocalDateTime.now(), endTime);
}
}
🎉 해결 결과
- ✅ 시험 타이머가 정상적으로 동작
- ✅ Redis 저장/조회 시 타입 변환 오류 해결
- ✅ 예외 상황에 대한 적절한 에러 처리 추가
💡 교훈 및 시사점
1. Redis 데이터 저장 시 고려사항
- 📌 Redis는 기본적으로 문자열 기반 저장소
- 📌 복잡한 객체 저장 시 직렬화 전략 신중히 선택 필요
- 📌 가능하면 단순한 형태로 데이터 저장이 바람직
2. 타입 안전성 확보
- 🛡️ 명시적인 타입 변환으로 안정성 확보
- 🛡️ 에러 발생 가능성 있는 부분에 대한 적절한 예외 처리
- 📝 로깅을 통한 문제 추적 용이성 확보
3. 설계 시 고려사항
- 🎯 캐시 데이터의 단순화가 유지보수성 향상에 도움
- 🎯 명확한 책임 분리와 에러 처리가 중요
- 📊 로깅을 통한 모니터링 체계 구축 필요
📚 관련 참고 자료
🏷️ Tags
#Redis #SpringBoot #Java #Serialization #Troubleshooting #LocalDateTime
🚨 문제 상황
시험 타이머 기능 구현 중 Redis에 LocalDateTime을 저장하고 불러오는 과정에서 직렬화 관련 에러 발생
🔍 원인 분석
1. RedisTemplate의 기본 직렬화 동작
2. 기존 코드의 문제점
✨ 해결 방법
1. RedisTemplate 타입 변경
2. 수정된 코드
🎉 해결 결과
💡 교훈 및 시사점
1. Redis 데이터 저장 시 고려사항
2. 타입 안전성 확보
3. 설계 시 고려사항
📚 관련 참고 자료
🏷️ Tags
#Redis#SpringBoot#Java#Serialization#Troubleshooting#LocalDateTime