【问题标题】:spring-data-redis, empty list attribute value becomes nullspring-data-redis,空列表属性值变为null
【发布时间】:2019-07-17 10:10:19
【问题描述】:

我正在将一些微服务从 SpringBoot1.5 移植到 2.1。

我们正在使用 spring-data-redis。似乎默认的内部从绝地转向生菜。

问题是我们现在观察到一些奇怪的行为,当我们保存一个对象然后检索它时,有一个微小的区别:

空列表属性被替换为 null。

这是一个例子:

//repo 
public interface TestRepository extends CrudRepository<Test, String> {}

...

//object
@RedisHash(timeToLive = 60) 
public static class Test{
    @Id private String id;
    int age;
    List<String> friends;
}

...

//saving then retreiving
Test test = new Test("1", 15, Collections.emptyList());
System.out.println(test);
testRepository.save(test);

Test testGet = testRepository.findById("1").get();
System.out.println(testGet);

接下来会发生什么:

//before
{
  "id": "1",
  "age": 15,
  "friends": []
}

//after 
{
  "id": "1",
  "age": 15
}

friends 空列表已消失。这种新行为会在许多地方影响我们的代码,导致 NullPointerExceptions 等。

显然,有多个序列化程序可用,但这似乎没有任何效果。任何的想法?

https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#redis:serializer

供参考:

        springBootVersion = '2.1.5.RELEASE'
        springCloudVersion = 'Greenwich.SR1'

【问题讨论】:

  • 这个问题不仅仅存在于 spring-boot。它也适用于 C#。
  • 我不知道这个问题的正确答案,但我通过将可序列化类中的字段写入List&lt;Object&gt; objects = new ArrayList&lt;&gt;(); 解决了这个问题

标签: spring-boot serialization spring-data-redis lettuce


【解决方案1】:

我也遇到了这个问题。我是这样解决的:

@RedisHash(timeToLive = 60) 
public class MyData implements Serializable {

    @Id
    private String id;
    
    
    private List<Object> objects = new ArrayList<>();
}

如果我将 MyData 与空列表 objects 一起保存,当我从 Redis 中提取它时,其中的 objects 将不会为空,而是空列表。如果我将保存'MyData'而不为空objects,则objects不会在反序列化后丢失。

【讨论】:

    猜你喜欢
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 2021-09-13
    • 2019-12-25
    • 1970-01-01
    • 2016-12-02
    • 1970-01-01
    相关资源
    最近更新 更多