|
| 1 | +package com.loopers.config.redis; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.annotation.JsonCreator; |
| 4 | +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; |
| 5 | +import com.fasterxml.jackson.annotation.JsonProperty; |
| 6 | +import com.fasterxml.jackson.databind.JsonNode; |
| 7 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 8 | +import com.fasterxml.jackson.databind.SerializationFeature; |
| 9 | +import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator; |
| 10 | +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; |
| 11 | +import org.springframework.context.annotation.Bean; |
| 12 | +import org.springframework.context.annotation.Configuration; |
| 13 | +import org.springframework.data.domain.PageImpl; |
| 14 | +import org.springframework.data.redis.connection.RedisConnectionFactory; |
| 15 | +import org.springframework.data.redis.core.RedisTemplate; |
| 16 | +import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; |
| 17 | +import org.springframework.data.redis.serializer.StringRedisSerializer; |
| 18 | + |
| 19 | +import java.util.List; |
| 20 | + |
| 21 | +@Configuration |
| 22 | +public class RedisConfig { |
| 23 | + |
| 24 | + @Bean |
| 25 | + public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) { |
| 26 | + RedisTemplate<String, Object> template = new RedisTemplate<>(); |
| 27 | + template.setConnectionFactory(connectionFactory); |
| 28 | + |
| 29 | + ObjectMapper objectMapper = new ObjectMapper(); |
| 30 | + |
| 31 | + objectMapper.registerModule(new JavaTimeModule()); |
| 32 | + objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); |
| 33 | + |
| 34 | + objectMapper.activateDefaultTyping( |
| 35 | + BasicPolymorphicTypeValidator.builder() |
| 36 | + .allowIfBaseType(Object.class) |
| 37 | + .build(), |
| 38 | + ObjectMapper.DefaultTyping.EVERYTHING |
| 39 | + ); |
| 40 | + |
| 41 | + objectMapper.addMixIn(PageImpl.class, PageImplMixin.class); |
| 42 | + |
| 43 | + GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer(objectMapper); |
| 44 | + |
| 45 | + template.setKeySerializer(new StringRedisSerializer()); |
| 46 | + template.setValueSerializer(serializer); |
| 47 | + template.setHashKeySerializer(new StringRedisSerializer()); |
| 48 | + template.setHashValueSerializer(serializer); |
| 49 | + |
| 50 | + return template; |
| 51 | + } |
| 52 | + |
| 53 | + @JsonIgnoreProperties(ignoreUnknown = true) |
| 54 | + abstract static class PageImplMixin<T> { |
| 55 | + @JsonCreator |
| 56 | + public PageImplMixin(@JsonProperty("content") List<T> content, |
| 57 | + @JsonProperty("pageable") JsonNode pageable, |
| 58 | + @JsonProperty("total") long total) { |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments