java - 无法将缓存的 json 数据反序列化为 AsyncResult

标签 java spring redis spring-cache

我正在使用带有 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/

相关文章:

Redisson本地缓存使用

java - 无法在 Eclipse 中创建 Android 应用程序项目。错误消息 - 输入应用程序名称(显示在启动器中)

Python-rq with flask + uwsgi + Nginx : Do I need more uwsgi processes or redis workers?

java - Spring自定义auth过滤器和自定义jwtfilter

java - java/spring 和 c++/qt 应用程序之间使用 websockets 进行通信

java - 在 Dart 中,有没有办法拦截对编程结构的访问和更改?

java - Spring Web 应用程序上的 Hibernate 集成

c# - 覆盖 Azure 上 RedisSessionStateProvider 的连接

java - 仅将鼠标悬停在使用 Selenium 的元素上

java - 循环到执行器服务