记录一些 Redis 缓存及 ObjectMapper 的配置。
Object Mapper
首先提供一个全局的 JsonMapper 作为 jackson 的 ObjectMapper,用于序列化和反序列化。
顺便解决 jsr310 相关的日期序列化问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.json.JsonMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
@Configuration public class JacksonConfig { @Bean public ObjectMapper jsonMapper() { return JsonMapper .builder() .findAndAddModules() .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) .build(); } }
|
Redis Cache Manager
RedisCacheManager 配置,使用 jsonMapper 作为序列化器,我们需要设置 DefaultTyping
以支持反序列化。
根据文档,此处我们选择 NON_FINAL_AND_ENUMS
,EVERYTHING
已经弃用且不建议使用。
更多信息可以参考:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.annotation.Resource; import lombok.RequiredArgsConstructor; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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.SerializationPair; import org.springframework.data.redis.serializer.RedisSerializer;
@EnableCaching @Configuration @RequiredArgsConstructor public class CacheConfig { @Resource(name = "jsonMapper") private final ObjectMapper jsonMapper;
@Bean public RedisCacheManager cacheManger(RedisConnectionFactory redisConnectionFactory) { RedisSerializer<Object> serializer = new GenericJackson2JsonRedisSerializer( jsonMapper .copy() .activateDefaultTyping( jsonMapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL_AND_ENUMS, JsonTypeInfo.As.PROPERTY ) );
return RedisCacheManager .builder(redisConnectionFactory) .cacheDefaults( RedisCacheConfiguration .defaultCacheConfig() .computePrefixWith(name -> name + ":") .disableCachingNullValues() .serializeValuesWith(SerializationPair.fromSerializer(serializer)) ) .build(); } }
|