Redis获取缓存异常:java.lang.ClassCastException: java.

家电修理 2023-07-16 19:17www.caominkang.com电器维修

Jackson2JsonRedisSerializer 
 

使用Jackson2JsonRedisSerializer缓存数据到redis,获取时出现的异常

需要配置Jackson2JsonRedisSerializer

// 配置Jackson2JsonRedisSerializer
 // 避免出现获取缓存时出现的类型转换错误
 private Jackson2JsonRedisSerializer jackson2JsonRedisSerializer() {
  Jackson2JsonRedisSerializer jackson2JsonRedisSerializer =
    ne Jackson2JsonRedisSerializer<>(Object.class);
  ObjectMapper objectMapper = ne ObjectMapper();
  objectMapper.setVisibility(PropertyAessor.ALL, JsonAutoDetect.Visibility.ANY);
  objectMapper.configure(MapperFeature.USE_ANNOTATIONS, false);
  objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

  // 此项必须配置,否则会报java.lang.ClassCastException: java.util.linkedHashMap cannot be cast to XXX
  objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
  objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
  jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
  return jackson2JsonRedisSerializer;
 }

 

该方法参考于https://.codeprj./blog/b1f3f91.html

RedisTemplate

 @Bean
 @ConditionalOnMissingBean(
   name = {"redisTemplate"}
 )
 public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) thros UnknonHostException {
  RedisTemplate template = ne RedisTemplate();
  template.setConnectionFactory(redisConnectionFactory);
  Jackson2JsonRedisSerializer jackson2RedisSerializer = jackson2JsonRedisSerializer();
  //默认使用jdk序列化,
  template.setDefaultSerializer(jackson2RedisSerializer);
  return template;
 }
 

RedisCacheManager

// //重写 RedisCacheConfiguration 类的cacheManager方法 并注入IOC容器
 @Primary   // 设置为默认缓存管理器
 @Bean
 public CacheManager cacheManager(RedisConnectionFactory factory){

  Jackson2JsonRedisSerializer jsonRedisSerializer = jackson2JsonRedisSerializer();

  RedisCacheConfiguration cacheManager =
    RedisCacheConfiguration.defaultCacheConfig()
      //设置缓存有效时间(1小时)
      .entryTtl(Duration.ofHours(1))
      //不缓存null结果,若出现null结果时会报异常
      .disableCachingNullValues()
      //以json形式序列化对象
      .serializevaluesWith(RedisSerializationContext.SerializationPair.fromSerializer(jsonRedisSerializer));


  return RedisCacheManager.builder(factory).cacheDefaults(cacheManager).build();
 }
 
        
        
               
      
    
    

  

Copyright © 2016-2025 www.caominkang.com 曹敏电脑维修网 版权所有 Power by