Hash mapping
使用Redis的hash结构存储对象有以下三种方式
1. 使用HashOperations和序列化(见上一节)
2. 使用Redis持久化(推荐,见后续章节)
3. 使用HashMapper和HashOperations
这里主要介绍第三种方式
HashMapper将对象与Map
ObjectHashMapper
@Repository("hashMapping")
public class HashMapping {
@Resource(name = "redisTemplate")
HashOperations<String, byte[], byte[]> hashOperations;
HashMapper<Object, byte[], byte[]> mapper = new ObjectHashMapper();
public <T> void writeHash(String key, T obj) {
Map<byte[], byte[]> mappedHash = mapper.toHash(obj);
hashOperations.putAll(key, mappedHash);
}
@SuppressWarnings("unchecked")
public <T> T loadHash(String key) {
Map<byte[], byte[]> loadedHash = hashOperations.entries(key);
return (T) mapper.fromHash(loadedHash);
}
}
测试方法
@Autowired
HashMapping hashMapping;
@Test
public void testHashMapping() {
String key = "SerializedRedisTemplateTest:TEST:hashMapping:1";
Student stu1 = new Student("1", 1);
hashMapping.writeHash(key, stu1);
Student result = hashMapping.loadHash(key);
Assert.assertEquals(stu1,result);
}
Jackson2HashMapper
Jackson2HashMapper支持普通映射和扁平映射两种方式。
对于类型
public class Person {
String firstname;
String lastname;
Address address;
}
public class Address {
String city;
String country;
}
普通映射结果为
Hash Field | Value |
---|---|
firstname | Jon |
lastname | Snow |
address | { “city” : “Castle Black”, “country” : “The North” } |
扁平映射结果为
Hash Field | Value |
---|---|
firstname | Jon |
lastname | Snow |
address.city | Castle Black |
address.country | The North |
扁平映射需要所有属性名称不含影响到JSON路径。 因此不支持在Map的key或属性名中使用点号和括号。