springboot2.0x 和springboot 1.0 整合redis 使用自定义CacheManager 问题

版权声明:版权为ZZQ所有 https://blog.csdn.net/qq_39148187/article/details/82630597

在springboot1.0 和springboot2.0 中默认的序列化都是使用的jdk的 Serializer  实现这个接口,jdk自带的序列化方法

在springboot1.0中如果向自定义我们呢直接创建cachemanager 然后传入redistemple模板对象, 就可以了, redistemple 模板对象中定制序列化的方式

    @Bean
    public RedisTemplate<Object, Employee> empRedisTemplate(
            RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate<Object, Employee> template = new RedisTemplate<Object, Employee>();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
        template.setDefaultSerializer(ser);
        return template;
    }
    @Bean
    public RedisCacheManager employeeCacheManager(RedisTemplate<Object, Employee> empRedisTemplate){
        RedisCacheManager cacheManager = new RedisCacheManager(empRedisTemplate);
        //key多了一个前缀

        //使用前缀,默认会将CacheName作为key的前缀
        cacheManager.setUsePrefix(true);

        return cacheManager;
    }

springboot2.0 中,使用rediscachemanager 就可以了

 @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisCacheConfiguration cacheConfiguration =
                RedisCacheConfiguration.defaultCacheConfig()
                        .entryTtl(Duration.ofDays(1))
                        .disableCachingNullValues()
                        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new
                                GenericJackson2JsonRedisSerializer()));
        return RedisCacheManager.builder(factory).cacheDefaults(cacheConfiguration).build();
    }

猜你喜欢

转载自blog.csdn.net/qq_39148187/article/details/82630597