我正在使用带有 redis 实现的 spring 缓存,我有以下方法
@Async
@Cacheable(key = "#id")
public Future<Student> getStudent(String id){
Student stu = ...;
return new AsyncResult<>(stu);
}
当我第一次访问该方法时,数据以json格式缓存到redis中。
但是当我第二次访问它时,出现了这样的错误:
java.util.concurrent.ExecutionException: org.springframework.data.redis.serializer.SerializationException: 无法读取 JSON: 无法构造 org.springframework.scheduling.annotation.AsyncResult
的实例(否创建者,如默认构造,存在):不能从对象值反序列化(没有基于委托(delegate)或属性的创建者)
[编辑]
我找到了一个解决方法:新建一个 MyAsyncReslt.java,它扩展了 AsyncResult 并添加了 NoArgsContructor。
最佳答案
Redis 序列化程序在后台使用 Jackson Class Jackson2JsonRedisSerializer ,错误:
Cannot construct instance of
org.springframework.scheduling.annotation.AsyncResult
(no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
似乎是 Jackson ( can't deserialize without default constructor ) 的结果:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of
Type
(no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
确保您的模型类 Student
结构正确,符合 Jackson Jackson - Object Serialization因为它通过泛型在 AsyncResult
中使用。
根据 OP 问题编辑:
I found a workaround : new a MyAsyncReslt.java which extends AsyncResult and add the NoArgsContructor.
Spring 的 AsyncResult
似乎没有正确实现以使用 Jackson 进行序列化(查看 Github spring-projects/spring-framework: AsyncResult )。
public class AsyncResult<V> implements ListenableFuture<V> {
// ...
public AsyncResult(@Nullable V value) {
this(value, null);
}
private AsyncResult(@Nullable V value, @Nullable Throwable ex) {
this.value = value;
this.executionException = ex;
}
// Missing empty constructor to comply with Jackson requirements:
public AsyncResult() {}
// ...
在问题得到修补之前,您可以扩展 Spring 的 AsyncResult
并提供所需的空构造函数。在代码中自由使用自定义 AsyncResult。
关于java - 无法将缓存的 json 数据反序列化为 AsyncResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56071987/