-
Redis - 카테고리 조회 적용이커머스 devops/국비교육 2025. 12. 6. 11:38
- JsonUtil 작성
@Slf4j @Component public class JsonUtil { private static final ObjectMapper objectMapper = new ObjectMapper() .registerModule(new JavaTimeModule()) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); public static <T> String toJson(T object) { try { return objectMapper.writeValueAsString(object); } catch (JsonProcessingException e) { log.error("JSON 직렬화 실패: {}", e.getMessage(), e); throw new ServiceException(ServiceExceptionCode.JSON_PROCESSING_ERROR); } } public static <T> T fromJson(String jsonString, Class<T> clazz) { try { return objectMapper.readValue(jsonString, clazz); } catch (JsonProcessingException e) { throw new ServiceException(ServiceExceptionCode.JSON_PROCESSING_ERROR); } } public static <T> List<T> fromJsonList(String jsonString, Class<T> clazz) { try { CollectionType type = objectMapper.getTypeFactory() .constructCollectionType(List.class, clazz); return objectMapper.readValue(jsonString, type); } catch (JsonProcessingException e) { throw new ServiceException(ServiceExceptionCode.JSON_PROCESSING_ERROR); } } }- CategoryController 추가
@RestController @RequiredArgsConstructor @RequestMapping("/api/categories") public class CategoryController { ... @GetMapping("/caches") public ResponseEntity<ApiResponse<List<CategoryResponse>>> findAllCategoriesByCaches(HttpSession session) { final String CATEGORY_CACHE_KEY = "cachedCategoriesJson"; String cachedCategoriesJson = (String) session.getAttribute(CATEGORY_CACHE_KEY); if (cachedCategoriesJson == null) { List<CategoryResponse> freshCategories = categoryService.getAllCategories(); session.setAttribute(CATEGORY_CACHE_KEY, JsonUtil.toJson(freshCategories)); return ResponseEntity.ok(ApiResponse.success(freshCategories, HttpStatus.OK)); } List<CategoryResponse> cachedCategories = JsonUtil.fromJsonList( cachedCategoriesJson, CategoryResponse.class ); return ResponseEntity.ok(ApiResponse.success(cachedCategories, HttpStatus.OK)); } ... }


처음 조회할 때 db > 재조 회할 때 redis에서 가져와야 하는데 JsonUtil 어딘가에서 문제가 생겼다

에러를 찍어보니 responseDto에 기본 생성자가 없어서 에러가 난 거였다

productResponse도 함께 가져오기 때문에 responseDto들에 어노테이션을 붙여주고 실행해 보니 두 번째 조회부터는 DB 타지 않고 조회되는 것을 확인할 수 있었다
[ 구조 ]
spring:session:sessions:{세션ID}
├── creationTime
├── lastAccessedTime
├── maxInactiveInterval.
└── sessionAttr:cachedCategoriesJson ← 여기에 저장됨- Redis Key : spring:session:sessions:{세션ID}
- Hash Field : sessionAttr:cachedCategoriesJson
- Hash Value : 실제 JSON 데이터
# 세션 데이터 전체 보기
HGETALL "spring:session:sessions:5d424e15-83b6-4d4f-89ae-c322d3cad9a5"
세션데이터에 들어가 보면 내가 지정해 둔 키이름으로 저장된 것 또한 확인할 수 있다
728x90'이커머스 devops > 국비교육' 카테고리의 다른 글
스프링시큐리티 적용 로그인 구현 및 비회원 주문 로직 추가 (0) 2025.12.14 P6Spy 적용하기 (0) 2025.11.22 Resolved [org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags: (0) 2025.11.22 실무 활용 - 스프링 데이터 JPA와 Querydsl (0) 2025.11.19 동적 쿼리와 성능 최적화 조회 (0) 2025.11.19