Spring Boot2.X与SpringBoot1.X配置Redis缓存的区别以及JSON格式保存到Redis中所遇到的问题

SpringBoot1.X配置RedisCacheManager

   @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;
    }
   //CacheManagerCustomizers可以来定制缓存的一些规则
    @Primary  //将某个缓存管理器作为默认的
    @Bean
    public RedisCacheManager employeeCacheManager(RedisTemplate<Object, Employee> empRedisTemplate){
        RedisCacheManager cacheManager = new RedisCacheManager(empRedisTemplate);
        //key多了一个前缀

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

        return cacheManager;
    }

SpringBoot2.X配置RedisCacheManager

 @Bean
   public RedisCacheManager employeeCacheManager(RedisConnectionFactory redisConnectionFactory){
       //创建Redis的序列化对象
       RedisSerializer<String> redisSerializer = new StringRedisSerializer();
       //使用Redis的模板配置json格式的对象
       RedisTemplate<Object, Employee> template = new RedisTemplate<>();
       template.setConnectionFactory(redisConnectionFactory);
       //创建redis使用json格式保存对象
       Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
       template.setDefaultSerializer(serializer);

       //配置序列化
       RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
               .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
               .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer));
           //redisConnectionFactory.usePrefix(true);
       //创建RedisCacheManager缓存器对象
       RedisCacheManager redisCacheManager = RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(redisCacheConfiguration).build();
       return redisCacheManager;
   }

Redis整合SpringBoot在保存对象数据的时候,默认的是使用jdk的序列化操作,如果需要保存json格式对象,则我们需要使用 jackson2JsonRedisSerializer对象进行操作

Spring Boot2.X与SpringBoot1.X配置Redis缓存的区别以及JSON格式保存到Redis中所遇到的问题_第1张图片
缓存的数据能存入redis;
* 第二次从缓存中查询就不能反序列化回来;
* 存的是dept的json数据;CacheManager默认使用RedisTemplate操作Redis,因此我们需要再为部门再定制一个缓存管理
*

你可能感兴趣的:(Spring Boot2.X与SpringBoot1.X配置Redis缓存的区别以及JSON格式保存到Redis中所遇到的问题)