RedisTemplate操作Redis数据:Hash类型

Redis的Hash可以存储多个KV对

NewImage

操作比较简单,如下

redis:0>hset testHash 0571 hangzhou
"1"
redis:0>hset testHash 021 shanghai
"1"
redis:0>hset testHash 010 beijing
"1"
redis:0>hkeys testHash

redis:0>getall testHash
"ERR unknown command 'getall'"
redis:0>hgetall testHash
 1)  "0571"
 2)  "hangzhou"
 3)  "021"
 4)  "shanghai"
 5)  "010"
 6)  "beijing"
redis:0>hget testHash 0571
"hangzhou"
redis:0>hget testHash 010
"beijing"
redis:0>hget testHash 021
"shanghai"
redis:0>hdel testHash 0571
"1"
redis:0>hgetall testHash
 1)  "021"
 2)  "shanghai"
 3)  "010"
 4)  "beijing"
redis:0>hdel testHash 021
"1"
redis:0>hdel testHash 010
"1"
redis:0>hgetall testHash

调用RedisTemplate如下

public class RedisTest extends BaseTest {

@Resource
private RedisTemplate redisTemplate;

@Test(description = "哈希散列")
public void redisHashTest() {
redisTemplate.opsForHash().put("testHash", "0571", "hangzhou");
redisTemplate.opsForHash().put("testHash", "021", "shanghai");
redisTemplate.opsForHash().put("testHash", "010", "beijing");
Assert.assertEquals(redisTemplate.opsForHash().get("testHash", "0571"), "hangzhou");
Assert.assertEquals(redisTemplate.opsForHash().get("testHash", "021"), "shanghai");
Assert.assertEquals(redisTemplate.opsForHash().get("testHash", "010"), "beijing");
redisTemplate.opsForHash().delete("testHash", "0571");
redisTemplate.opsForHash().delete("testHash", "021");
redisTemplate.opsForHash().delete("testHash", "010");
System.out.println(redisTemplate.opsForHash().size("testHash"));
}
}

比较直接

发表评论