1.首先需要maven引入 <dependency> ? ? ? ? ? ? <artifactId>jackson-datatype-jsr310</artifactId> ? ? ? ? ? ? <groupId>com.fasterxml.jackson.datatype</groupId> ? ? ? ? ? ? <version>2.15.3</version> ?</dependency>
? ? ? ? 2.示例代码如下
private RedisTemplate<String, Object> serializer(RedisTemplate<String, Object> redisTemplate) {
// LocalDate序列化
ObjectMapper mapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
// 设置序列化格式
javaTimeModule.addSerializer(LocalDateTime.class,
new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
mapper.registerModule(javaTimeModule);
// 使用 FastJsonRedisSerializer 来序列化和反序列化redis 的 value的值
Jackson2JsonRedisSerializer<Object> fastJsonRedisSerializer = new Jackson2JsonRedisSerializer<>(mapper,Object.class);
// key 的 String 序列化采用 StringRedisSerializer
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
// value 的值序列化采用 fastJsonRedisSerializer
redisTemplate.setValueSerializer(fastJsonRedisSerializer);
redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}