Jackson2JsonRedisSerializer.setObjectMapper(objectMapper)不生效在springboot2.6.13中
时间: 2024-04-11 22:27:11 浏览: 196
在Spring Boot 2.6.13中,`Jackson2JsonRedisSerializer`的`setObjectMapper()`方法不再生效。这是因为在这个版本的Spring Boot中,Redis的默认序列化器已经从`Jackson2JsonRedisSerializer`更改为`LettuceConnectionFactory`。
要解决这个问题,你可以使用`LettuceConnectionFactory`来配置自定义的序列化器。以下是一个示例:
```java
@Configuration
public class RedisConfig {
@Bean
public LettuceConnectionFactory redisConnectionFactory() {
LettuceConnectionFactory factory = new LettuceConnectionFactory();
factory.setHostName("localhost");
factory.setPort(6379);
factory.setDatabase(0);
// 配置自定义的序列化器
RedisSerializationContext.SerializationPair<Object> serializationPair = RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer());
RedisSerializationContext<Object, Object> serializationContext = RedisSerializationContext.newSerializationContext().key(serializationPair).value(serializationPair).build();
factory.setKeySerializer(new StringRedisSerializer());
factory.setValueSerializer(redisSerializer());
factory.setHashKeySerializer(new StringRedisSerializer());
factory.setHashValueSerializer(redisSerializer());
return factory;
}
private RedisSerializer<Object> redisSerializer() {
// 使用Jackson2JsonRedisSerializer作为自定义的序列化器
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
return new Jackson2JsonRedisSerializer<>(Object.class);
}
}
```
在上述示例中,我们使用`LettuceConnectionFactory`来配置Redis连接工厂,并通过`setKeySerializer()`、`setValueSerializer()`、`setHashKeySerializer()`和`setHashValueSerializer()`方法设置自定义的序列化器。
请确保你将以上的配置类正确注入到Spring Boot应用程序中,这样就可以正确地使用自定义的序列化器了。
阅读全文