使用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) {...}
有没有办法实现
停止存储此信息
反序列化时忽略此
反序列化为具有相同属性的不同类对象的方法
最佳答案
我刚刚在同一个问题上花了半天时间,所以把答案留在这里供后代使用:
通常,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 对象将独立于类包名称进行反序列化。
关于serialization - 反序列化成另一个类——Spring data redis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59610666/