欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

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

时间:2023-07-11

Jackson2JsonRedisSerializer

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

需要配置Jackson2JsonRedisSerializer

// 配置Jackson2JsonRedisSerializer // 避免出现获取缓存时出现的类型转换错误 private Jackson2JsonRedisSerializer jackson2JsonRedisSerializer() { Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.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://www.codeprj.com/blog/b1f3f91.html

RedisTemplate

@Bean @ConditionalOnMissingBean( name = {"redisTemplate"} ) public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException { RedisTemplate template = new 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-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。