Redis实战 - 3.Hash

hash

Redis的Hash有点像一个对象(object),一个Hash里面可以存多个Key-Value对作为它的field,所以它通常可以用来表示对象。

Hash里面能存放的值也能作为String类型来存储,如果Hash里面值的类型可以解析为数字,那么也可以进行自增自减等操作。
hash

HSET HGET

HSET 设置Hash里面的值:
语法:HSET KEY_NAME FIELD VALUE

127.0.0.1:6379> HSET myhash field1 "foo"
(integer) 1
redis 127.0.0.1:6379> HGET myhash field1
"foo"

HMSET HMGET

HMSET:同时将多个 field-value (字段-值)对设置到哈希表中。
语法: HMSET KEY_NAME FIELD1 VALUE1 ...FIELDN VALUEN

HMGET:返回哈希表中,一个或多个给定字段的值
语法:HMGET KEY_NAME FIELD1...FIELDN

127.0.0.1:6379> HMSET myhash field1 "Hello" field2 "World"
OK
127.0.0.1:6379> HMGET MYHASH field1
1) (nil)
127.0.0.1:6379> HMGET myhash field1
1) "Hello"
127.0.0.1:6379> HMGET myhash field1 field2
1) "Hello"
2) "World"

HGETALL

如果想获得Hash所有的Key-Value对,那就使用HGETALL:

127.0.0.1:6379> hgetall myhash
1) "field1"
2) "Hello"
3) "field2"
4) "World"
127.0.0.1:6379>

HDEL

HDEL key field1 [field2]
删除一个或多个哈希表字段

redis 127.0.0.1:6379> HSET myhash field1 "foo"
(integer) 1
redis 127.0.0.1:6379> HDEL myhash field1
(integer) 1
redis 127.0.0.1:6379> HDEL myhash field2
(integer) 0

HEXISTS

HEXISTS key field
查看哈希表 key 中,指定的字段是否存在。

redis 127.0.0.1:6379> HSET myhash field1 "foo"
(integer) 1
redis 127.0.0.1:6379> HEXISTS myhash field1
(integer) 1
redis 127.0.0.1:6379> HEXISTS myhash field2
(integer) 0

HINCRBY

如果Hash里某个Field值的类型可以解析成数值,那么还可以用HINCRBY来做自增:

127.0.0.1:6379> hincrby user:1000 age 1
(integer) 1
127.0.0.1:6379> hincrby user:1000 age 1
(integer) 2
127.0.0.1:6379> hincrby user:1000 age 1
(integer) 3
127.0.0.1:6379> hincrby user:1000 age -1
(integer) 2
127.0.0.1:6379>

HINCRBYFLOAT

HINCRBYFLOAT key field increment
为哈希表 key 中的指定字段的浮点数值加上增量 increment 。

redis> HSET mykey field 10.50
(integer) 1
redis> HINCRBYFLOAT mykey field 0.1
"10.6"
redis> HINCRBYFLOAT mykey field -5
"5.6"
redis> HSET mykey field 5.0e3
(integer) 0
redis> HINCRBYFLOAT mykey field 2.0e2
"5200"
redis> 

HKEYS

HKEYS key
获取所有哈希表中的字段

redis 127.0.0.1:6379> HSET myhash field1 "foo"
(integer) 1
redis 127.0.0.1:6379> HSET myhash field2 "bar"
(integer) 1
redis 127.0.0.1:6379> HKEYS myhash
1) "field1"
2) "field2"

HLEN

HLEN key
获取哈希表中字段的数量

redis 127.0.0.1:6379> HSET myhash field1 "foo"
(integer) 1
redis 127.0.0.1:6379> HSET myhash field2 "bar"
(integer) 1
redis 127.0.0.1:6379> HLEN myhash
(integer) 2

HSETNX

HSETNX key field value
只有在字段 field 不存在时,设置哈希表字段的值。

如果哈希表不存在,一个新的哈希表被创建并进行 HSET 操作。
如果字段已经存在于哈希表中,操作无效。
如果 key 不存在,一个新哈希表被创建并执行 HSETNX 命令。

redis 127.0.0.1:6379> HSETNX myhash field1 "foo"
(integer) 1
redis 127.0.0.1:6379> HSETNX myhash field1 "bar"
(integer) 0
redis 127.0.0.1:6379> HGET myhash field1
"foo"

redis 127.0.0.1:6379> HSETNX nosql key-value-store redis
(integer) 1

redis 127.0.0.1:6379> HSETNX nosql key-value-store redis       # 操作无效, key-value-store 已存在
(integer) 0

HVALS

HVALS key
获取哈希表中所有值

redis 127.0.0.1:6379> HSET myhash field1 "foo"
(integer) 1
redis 127.0.0.1:6379> HSET myhash field2 "bar"
(integer) 1
redis 127.0.0.1:6379> HVALS myhash
1) "foo"
2) "bar"

# 空哈希表/不存在的key

redis 127.0.0.1:6379> EXISTS not_exists
(integer) 0

redis 127.0.0.1:6379> HVALS not_exists
(empty list or set)

用.NET Core操练HASH

准备工作

1.建一个Person类

   class Person
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime JoinDate { get; set; }
        public int Age { get; set; }
        public decimal BankBlance { get; set; }
    }

2.然后从网上抄袭了一个C#对象Redis HashEntry[]之间转换的工具类:

   static class RedisHelper
    {
        public static HashEntry[] ToHashEntries(this object obj)
        {
            PropertyInfo[] properties = obj.GetType().GetProperties();
            return properties.Select(propertype =>
                                 new HashEntry(propertype.Name, propertype.GetValue(obj).ToString()))
                             .ToArray();
        }

        public static T ConvertFromRedis<T>(this HashEntry[] hashEntries)
        {
            PropertyInfo[] properties = typeof(T).GetProperties();
            var obj = Activator.CreateInstance(typeof(T));
            foreach (var property in properties)
            {
                HashEntry entry = hashEntries.FirstOrDefault(g => g.Name.ToString().Equals(property.Name));
                 if(entry.Equals(new HashEntry())){ continue;}
                property.SetValue(obj, Convert.ChangeType(entry.Value.ToString(), property.PropertyType));
            }
            return (T) obj;
        }
    }

命令测试

		static void Hash()
        {
            using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost:6379"))
            {

                IDatabase db = redis.GetDatabase();

                var person = new Person();
                person.Id = 123;
                person.FirstName = "Nick";
                person.LastName = "Carter";
                person.JoinDate = new DateTime(2019,4,20);
                person.Age = 32;
                person.BankBlance = 567.43m;

                //1.HSET 
                db.HashSet("user:123", person.ToHashEntries());
                
                //2.HGETALL  获取所有
                HashEntry[] entries = db.HashGetAll("user:123");
                foreach (HashEntry entry in entries)
                {
                    Console.WriteLine(entry.Name);
                }
                Console.WriteLine();

                //获取这个对象
                Console.WriteLine("获取这个对象");
                var thePerson = entries.ConvertFromRedis<Person>();
                Console.WriteLine(thePerson.FirstName); //Nick
                Console.WriteLine(thePerson.Age);       //32
                Console.WriteLine();

                
                //3.HGET 获取一个
                var age = db.HashGet("user:123", nameof(person.Age));
                Console.WriteLine(age);//32
                Console.WriteLine();

                //4.HMGET 获取多个
                RedisValue[] values = db.HashGet("user:123",
                    new RedisValue[]
                    {
                        nameof(person.Id), nameof(person.FirstName), nameof(person.Age), nameof(person.BankBlance),
                    });
                foreach (RedisValue redisValue in values)
                {
                    Console.WriteLine(redisValue);
                }
                // 123
                // Nick
                // 32
                // 567.43
                Console.WriteLine();
                
                //5.HINCRBY 自增整数
                var ageIncrement = db.HashIncrement("user:123", nameof(person.Age));
                Console.WriteLine(ageIncrement); //33
                ageIncrement = db.HashIncrement("user:123", nameof(person.Age),5);
                 Console.WriteLine(ageIncrement); //38
                Console.WriteLine();

                //6.HDEL 删除
                var ageDelSuccess = db.HashDelete("user:123", nameof(person.Age));
                Console.WriteLine(ageDelSuccess); //true
                var ageDel = db.HashGet("user:123", nameof(person.Age));
                Console.WriteLine(ageDel);  //null

                //7.HSCAN 迭代
                IEnumerable<HashEntry> entriesEnumerable = db.HashScan("user:123");
                foreach (HashEntry hashEntry in entriesEnumerable)
                {
                    Console.WriteLine($"{hashEntry.Name}:{hashEntry.Value}");
                }
                // Id: 123
                // FirstName: Nick
                // LastName:Carter
                // JoinDate:2019 / 4 / 20 0:00:00
                // BankBlance: 567.43
            }
        }

HSCAN

HSCAN key cursor [MATCH pattern] [COUNT count]
迭代哈希表中的键值对。
http://www.redis.cn/commands/hscan.html

参考:

草根专栏,Redis in .NET Core 入门:(3) Hash
runoob,Redis 哈希(Hash)

posted @ 2019-04-13 21:28  【唐】三三  阅读(741)  评论(0编辑  收藏  举报