Redis獲取緩存異常:java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to XXX

Redis獲取緩存異常:java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to XXX。java

出現這種異常,我須要自定義ObjectMapper,設置一些參數,而不是直接使用Jackson2JsonRedisSerializer類中黙認的ObjectMapper,看源代碼能夠知道,Jackson2JsonRedisSerializer中的ObjectMapper是直接使用new ObjectMapper()建立的,這樣ObjectMapper會將Redis中的字符串反序列化爲java.util.LinkedHashMap類型,致使後續Spring對其進行轉換成報錯。其實咱們只要它返回Object類型就能夠了。redis

使用如下方法,構建一個Jackson2JsonRedisSerializer對象,將其注入RedisCacheConfiguration便可。緩存

 

 

 private Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer() { Jackson2JsonRedisSerializer<Object> 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; } @Bean public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory){ //初始化一個RedisCacheWriter輸出流 RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory); //採用Jackson2JsonRedisSerializer序列化機制 // Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(Object.class); //建立一個RedisSerializationContext.SerializationPair給定的適配器pair RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer()); //建立CacheConfig RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair); return new RedisCacheManager(redisCacheWriter, defaultCacheConfig); } 
相關文章
相關標籤/搜索