Object to Hash Mapping Object 与 Hash 的映射
Redis 仓储支持将Objects 持久化到 Hashs。这需要RedisConverter 将Object 转换为Hash。默认的转换器实现是将属性值和Redis 原生的字节数组进行转换。
上节提到的Person 类型对应的映射如下:
_class = org.example.Person
id = e2c7dcee-b8cd-4424-883e-736ce564363e
firstname = rand
lastname = al’thor
address.city = emond's field
address.country = andor
The _class attribute is included on root level as well as on any nested interface or abstract types.
Simple property values are mapped by path.
Properties of complex types are mapped by their dot path.
在CustomConversions 中注册相应的Converter ,用户可以自定义映射行为。这些转换器负责byte[] 和 Map<String,byte[]>
的转换,byte[] 仍然使用默认映射散列结构,如将一个复杂的类型转换为一个二进制的JSON表现;而Map<String,byte[]>
则可以完全控制产生的hash。当写一个objects 到Redis hash 时,会删除从hash 中删除它的内容,然后重建整个hash,所以没有映射的数据会丢失。
Example 9. Sample byte[] Converters
@WritingConverter
public class AddressToBytesConverter implements Converter<Address, byte[]> {
private final Jackson2JsonRedisSerializer<Address> serializer;
public AddressToBytesConverter() {
serializer = new Jackson2JsonRedisSerializer<Address>(Address.class);
serializer.setObjectMapper(new ObjectMapper());
}
@Override
public byte[] convert(Address value) {
return serializer.serialize(value);
}
}
@ReadingConverter
public class BytesToAddressConverter implements Converter<byte[], Address> {
private final Jackson2JsonRedisSerializer<Address> serializer;
public BytesToAddressConverter() {
serializer = new Jackson2JsonRedisSerializer<Address>(Address.class);
serializer.setObjectMapper(new ObjectMapper());
}
@Override
public Address convert(byte[] value) {
return serializer.deserialize(value);
}
}
Using the above byte[] Converter produces eg.
_class = org.example.Person
id = e2c7dcee-b8cd-4424-883e-736ce564363e
firstname = rand
lastname = al’thor
address = { city : "emond's field", country : "andor" }
Example 10. Sample Map
@WritingConverter
public class AddressToMapConverter implements Converter<Address, Map<String,byte[]>> {
@Override
public Map<String,byte[]> convert(Address source) {
return singletonMap("ciudad", source.getCity().getBytes());
}
}
@ReadingConverter
public class MapToAddressConverter implements Converter<Address, Map<String, byte[]>> {
@Override
public Address convert(Map<String,byte[]> source) {
return new Address(new String(source.get("ciudad")));
}
}
Using the above Map Converter produces eg.
_class = org.example.Person
id = e2c7dcee-b8cd-4424-883e-736ce564363e
firstname = rand
lastname = al’thor
ciudad = "emond's field"
自定义转换器对索引没有影响。二级索引对自定义转换类型来说仍然可以创建。