Spring Data Redis入门示例:Hash操作(七)

时间:2023-03-10 07:59:15
Spring Data Redis入门示例:Hash操作(七)

将对象存为Redis中的hash类型,可以有两种方式,将每个对象实例作为一个hash进行存储,则实例的每个属性作为hashfield;同种类型的对象实例存储为一个hash,每个实例分配一个field,将对象序列化后,作为该field的值;

假设有Person类:

public class Person {
private String name;
private String age;
……
}

第一种方式存储的结果为:

Spring Data Redis入门示例:Hash操作(七)

第二种方式存储的结果为:

Spring Data Redis入门示例:Hash操作(七)

因此,Spring Data Redis处理hash类型数据一般有两种策略:

  • 使用HashOperationsJson序列化器直接映射
  • 使用HashMapperHashOperations

实例代码如下:

@Autowired
private RedisTemplate template; @Resource(name = "redisTemplate")
private HashOperations<String, String, Object> hashOps; public void test(){
// 使用HashOperations和json序列化器,存储hash
Map<String, String> map = new HashMap<String, String>();
map.put("name", "wangdh");
map.put("age", "26"); // 会将map进行json序列化,存储为field为1,对应的值
hashOps.put("person", "1", map); // 使用HashMapper和HashOperations,存储hash
// 存储的数据会多出一个键:@class,标识序列化的类型
HashMapper<Object, String, Object> mapper = new Jackson2HashMapper(false);
Map<String, Object> mappedHash = mapper.toHash(map);
hashOps.putAll("person2",mappedHash); // 直接将map作为hash存储
hashOps.putAll("person3",map);
}

HashMappers

HashMappers使对象和Map <K,V>进行相互转换,有多种默认的实现方式可供使用:

  • 基于Spring’s BeanUtilsBeanUtilsHashMapper
  • 使用Object to Hash MappingObjectHashMapper(使用JDK序列化器)
  • 使用FasterXML JacksonJackson2HashMapper(常用,使用Json序列化器)

Jackson2HashMapper可以将数据*属性映射为哈希字段名称,并可选地将结构展平。

简单的类型映射到简单的值。复杂类型(嵌套对象,集合,映射)表示为嵌套JSON

展平会为所有嵌套属性创建单独的哈希条目,并尽可能将复杂类型解析为简单类型。

展开的形式:

{
"firstname":"Jon",
"lastname":"Snow",
"address.city":"Castle Black",
"address.country":"The North"
}

不展平的形式:

{
"firstname":"Jon",
"lastname":"Snow",
"address":
{
"city" : "Castle Black",
"country" : "The North"
}
}