我使用 spring Data Redis Reactive 框架,spring Boot 版本是 2.3.0。
这是我的 Redis 配置:
@Bean("reactiveRedisTemplate")
public ReactiveRedisTemplate<String, Object> reactiveRedisTemplateString(ReactiveRedisConnectionFactory connectionFactory) {
Jackson2JsonRedisSerializer jacksonSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
JavaTimeModule timeModule = new JavaTimeModule();
timeModule.addSerializer(Date.class, new DateSerializer(Boolean.FALSE, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));
timeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
timeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
timeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
timeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
timeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
timeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
objectMapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);
objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
objectMapper.registerModule(timeModule).registerModule(new ParameterNamesModule()).registerModules(ObjectMapper.findModules());
jacksonSerializer.setObjectMapper(objectMapper);
final StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
RedisSerializationContext<String , Object> serializationContext = RedisSerializationContext
.<String, Object>newSerializationContext()
.key(stringRedisSerializer)
.value(jacksonSerializer)
.hashKey(stringRedisSerializer)
.hashValue(jacksonSerializer)
.build();
return new ReactiveRedisTemplate(connectionFactory, serializationContext);
}
我使用 hashoperations.put 方法设置了一个 LocalDateTime 对象,以在 Redis 中显示以下表单:
key hashKey "2020-06-23 16:42:44"
当我使用 Mono<LocalDateTime>Mono = hashoperations.get(key,hashKey) 获取值时,会发生以下异常:
java.lang.ClassCastException: class java.lang.String cannot be cast to class java.time.LocalDateTime (java.lang.String and java.time.LocalDateTime are in module java.base of loader 'bootstrap')
at reactor.core.publisher.FluxFilter$FilterSubscriber.onNext(FluxFilter.java:93)
at reactor.core.publisher.MonoNext$NextSubscriber.onNext(MonoNext.java:76)
但是当 LocalDateTime 是对象的属性时,就没有问题了。
我不知道如何解决它。谢谢你的所有答案。