美文网首页
关于SpringBoot集成RedisCache的序列化相关配置

关于SpringBoot集成RedisCache的序列化相关配置

作者: just_like_you | 来源:发表于2019-08-01 17:15 被阅读0次

    记录一下在Spring Cache中集成Redis的相关序列化配置

    • 可以继承CachingConfigurerSupport来进行扩展CacheManagerKeyGenerator相关组件
    @Configuration
    @EnableCaching
    public class RedisConfig extends CachingConfigurerSupport {
    
        /**
         * 配置redis的value 序列化策略
         *
         * @return
         */
        @Bean
        public RedisCacheConfiguration redisCacheConfiguration() {
            Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
            RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
            configuration = configuration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)).entryTtl(Duration.ofDays(30));
            return configuration;
        }
    
        /**
         * 配置RedisTemplate序列化方式
         *
         * @param connectionFactory
         * @return
         */
        @Bean
        public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
            RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
            redisTemplate.setConnectionFactory(connectionFactory);
    
            // 使用Jackson2JsonRedisSerialize替换默认序列化
            Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    
            jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
    
            // 设置key和value的序列化规则
            redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            redisTemplate.afterPropertiesSet();
    
            return redisTemplate;
        }
    }
    

    相关文章

      网友评论

          本文标题:关于SpringBoot集成RedisCache的序列化相关配置

          本文链接:https://www.haomeiwen.com/subject/zxecdctx.html