反序列化为另一个类-Spring数据重做

问题描述 投票:1回答:1

正在处理Spring Data Redis我序列化一个对象并将其存储到Redis中。序列化策略为Jackson2JsonRedisSerializer。因此,假设我的bean是Sample.java,具有某些属性prop1, prop2,下面是如何将其添加到缓存中]

\xAC\xED\x00\x05sr\x00'com.main.model.Sample\x90\x91\xFB4\xDD\x9D\xE1\xBB\x02\x00\x11J\x00\x0Bprop1J\x00\x0Aprop2J

我们可以看到对象类型信息Sample也以其完全限定的名称存储。

现在,有多个服务可通过反序列化和更新该条目并将其写回到缓存中来对该条目进行处理。 (各种服务中的模型/ bean具有不同的完全限定名称)

[当其他服务尝试对它进行反序列化但失败,并显示ClassNotFoundException时,会发生此问题

    org.springframework.data.redis.serializer.SerializationException:         
       Cannot serialize; nested exception is 
       org.springframework.core.serializer.support.SerializationFailedException: 
       Failed to deserialize object type; 
       nested exception is java.lang.ClassNotFoundException: com.xyz.model.BasicSample

这里是一个样本

服务1

    @Override
    @Cacheable(value = "sample", key = "{ #sample.sampleId }", unless = "#result == null")
    public Sample fetchSample(Sample sample) {...}

服务2

    @Override
    @Cacheable(value = "sample", key = "{ #sample.sampleId }", unless = "#result == null")
    public BasicSample fetchBasicSample(BasicSample sample) {...}

是否有办法

  • 停止存储此信息

  • 反序列化时忽略此

  • 一种反序列化为具有相同属性的不同类对象的方法

serialization json-deserialization spring-data-redis
1个回答
1
投票

我在同一个问题上只花了半天,所以答案留给后代:

通常,Spring Data Redis将使用完整的类名作为_class键,但是开发人员可以使用@TypeAlias("someAlias")注释对其进行自定义。这将覆盖_class字段。

因此您可以将两个类定义为:

package com.example.service1;

import org.springframework.data.annotation.TypeAlias;
import org.springframework.data.redis.core.RedisHash;
import org.springframework.data.redis.core.index.Indexed;

@RedisHash(value = "sample")
@TypeAlias("SampleType")
public class Sample {
    @Indexed
    int id;

    String name;
    ...
}
package com.example.service2;

import org.springframework.data.annotation.TypeAlias;
import org.springframework.data.redis.core.RedisHash;
import org.springframework.data.redis.core.index.Indexed;

@RedisHash(value = "sample")
@TypeAlias("SampleType")
public class Sample {
    @Indexed
    int id;

    String name;
    ...
}

现在,将独立于类包名称反序列化redis对象。

Link to the relevant documentation for more info

© www.soinside.com 2019 - 2024. All rights reserved.