From 2de850ee2d89494a3f57b500ca62cdad38b1f2fe Mon Sep 17 00:00:00 2001 From: hmmini Date: Tue, 15 Oct 2024 16:08:37 +0900 Subject: [PATCH] =?UTF-8?q?[dev]=20=EC=83=81=ED=92=88=20=EC=A1=B0=ED=9A=8C?= =?UTF-8?q?=20=EC=84=B1=EB=8A=A5=20=EA=B0=9C=EC=84=A0=20-=20=EC=BA=90?= =?UTF-8?q?=EC=8B=9C=20AOP=20=EC=A0=81=EC=9A=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit issue: 140 --- .../commons/config/RedisCacheConfig.java | 47 +++++++++++++++++++ .../product/service/ProductService.java | 32 ++----------- src/main/resources/application.yml | 3 ++ 3 files changed, 53 insertions(+), 29 deletions(-) create mode 100644 src/main/java/com/mini/joymall/commons/config/RedisCacheConfig.java diff --git a/src/main/java/com/mini/joymall/commons/config/RedisCacheConfig.java b/src/main/java/com/mini/joymall/commons/config/RedisCacheConfig.java new file mode 100644 index 0000000..33feb30 --- /dev/null +++ b/src/main/java/com/mini/joymall/commons/config/RedisCacheConfig.java @@ -0,0 +1,47 @@ +package com.mini.joymall.commons.config; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator; +import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.cache.CacheKeyPrefix; +import org.springframework.data.redis.cache.RedisCacheConfiguration; +import org.springframework.data.redis.cache.RedisCacheManager; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.RedisSerializationContext; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +import java.time.Duration; + +@EnableCaching +@Configuration +public class RedisCacheConfig { + + @Bean + public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory) { + PolymorphicTypeValidator typeValidator = BasicPolymorphicTypeValidator + .builder() + .allowIfSubType(Object.class) + .build(); + + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.registerModule(new JavaTimeModule()); + objectMapper.activateDefaultTyping(typeValidator, ObjectMapper.DefaultTyping.NON_FINAL); + GenericJackson2JsonRedisSerializer redisSerializer = new GenericJackson2JsonRedisSerializer(objectMapper); + + RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() + .disableCachingNullValues() + .entryTtl(Duration.ofSeconds(120)) + .computePrefixWith(CacheKeyPrefix.simple()) + .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) + .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)); + + return RedisCacheManager.builder(connectionFactory) + .cacheDefaults(cacheConfiguration) + .build(); + } +} diff --git a/src/main/java/com/mini/joymall/product/service/ProductService.java b/src/main/java/com/mini/joymall/product/service/ProductService.java index ac0dcba..b933f49 100644 --- a/src/main/java/com/mini/joymall/product/service/ProductService.java +++ b/src/main/java/com/mini/joymall/product/service/ProductService.java @@ -1,53 +1,27 @@ package com.mini.joymall.product.service; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.mini.joymall.product.domain.entity.Product; import com.mini.joymall.product.domain.repository.ProductRepository; import com.mini.joymall.product.dto.ProductDTO; import com.mini.joymall.product.dto.response.ProductPageResponse; import lombok.RequiredArgsConstructor; +import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Service; import java.util.List; -import java.util.NoSuchElementException; @Service @RequiredArgsConstructor public class ProductService { private final ProductRepository productRepository; - private final RedisTemplate redisTemplate; - private final ObjectMapper objectMapper; + @Cacheable(value = "products", key = "#keyword + '::' + #pageable.pageNumber + '::' + #pageable.pageSize") public ProductPageResponse search(String keyword, Pageable pageable) { - String cacheKey = "searchProducts::" + keyword + "::" + pageable.getPageNumber() + "::" + pageable.getPageSize(); - String cachedData = redisTemplate.opsForValue().get(cacheKey); - if (cachedData != null) { - try { - System.out.println("redis에 캐시된 정보를 가져온다."); - System.out.println(cachedData); - return objectMapper.readValue(cachedData, ProductPageResponse.class); - } catch (Exception e) { - System.err.println("캐시된 데이터 역직렬화 중 오류 발생: " + e.getMessage()); - } - } - List productDTOS = productRepository.findProductsByNameStartsWith(keyword, pageable.getPageSize(), pageable.getOffset()); long total = productRepository.countProductsByNameRange(keyword); Page productPages = new PageImpl<>(productDTOS, pageable, total); - ProductPageResponse response = ProductPageResponse.from(productPages); - - try { - String jsonResponse = objectMapper.writeValueAsString(response); - redisTemplate.opsForValue().set(cacheKey, jsonResponse); - System.out.println("검색 결과를 Redis에 캐시한다."); - } catch (Exception e) { - System.err.println("겸색 결과 캐싱 중 오류 발생" + e.getMessage()); - } - return response; + return ProductPageResponse.from(productPages); } } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 007c205..37203b1 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -122,6 +122,9 @@ logging: springframework: jdbc: core: debug + cache: TRACE + data: + redis: DEBUG ---