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或属性名中使用点号和括号。
本文介绍了如何使用Redis的Hash结构来存储对象,通过三种不同的方法实现:HashOperations与序列化、Redis持久化及HashMapper结合HashOperations。重点讲解了第三种方法,并通过示例展示了如何使用HashMapper将对象写入Redis及从Redis加载对象。此外还介绍了Jackson2HashMapper支持的普通映射和平坦映射,展示了不同类型数据的映射结果。
923

被折叠的 条评论
为什么被折叠?



