StackExchange.Redis 之 hash 类型示例

StackExchange.Redis 的组件封装示例网上有很多,自行百度搜索即可。

这里只演示如何使用Hash类型操作数据:

1             // 在 hash 中存入或修改一个值  并设置order_hashkey有效期1分钟,过期自动删除;null为不过期
2             stopwatch.Start();
3             var isok = RedisCacheHelper.Instance.HashSet("order_hashkey", "order_hashfield", "10", TimeSpan.FromMinutes(1));
4             stopwatch.Stop();
5             Console.WriteLine("在hash中存入一个值消耗时间:" + stopwatch.ElapsedMilliseconds.ToString());  

1             //判断该字段是否存在 hash 中
2             var isexists = RedisCacheHelper.Instance.HashExists("order_hashkey", "order_hashfield");
3             Console.WriteLine("判断该字段是否存在hash中:" + isexists);  //返回 True 或 False

             //从hash中移除指定字段
             var isdel = RedisCacheHelper.Instance.HashDelete("order_hashkey", "order_hashfield");
             Console.WriteLine("从hash中移除指定字段:" + isdel);  //返回 True 或 False
            //从hash中递增  默认按1递增
            var getincre = RedisCacheHelper.Instance.HashIncrement("order_hashkey", "order_hashfield");
            Console.WriteLine("从hash中递增:" + getincre);  //返递增后的值 11

            //从hash中递减  默认按1递减
            var getdecre = RedisCacheHelper.Instance.HashDecrement("order_hashkey", "order_hashfield");
            Console.WriteLine("从hash中递减:" + getdecre);  //返递减后的值  10

            //保存一个字符串类型集合
            string[] strarray = { "1", "2", "3", "4", "5" };
            RedisCacheHelper.Instance.HashSetList("orderlist_hashkey", strarray, m => { return "hashfield_" + m.ToString(); }, new TimeSpan(0, 0, 50));

            //从数据库获取10条数据
            stopwatch.Start();
            var getlist = TestRedis.GetOrderFormAll(10);
            stopwatch.Stop();
            Console.WriteLine("从数据库获取10条数据消耗时间:" + stopwatch.ElapsedMilliseconds.ToString());

            //保存多个对象集合 非序列化
            stopwatch.Start();
            RedisCacheHelper.Instance.HashSetObjectList("objlist_hashkey", getlist, r => { return r.ordercode.ToString(); }, 1);
            stopwatch.Stop();
            Console.WriteLine("将10条数据存入HashRedis 消耗时间:" + stopwatch.ElapsedMilliseconds.ToString());

            //保存或修改一个hash对象(序列化) 对key设置过期时间有时候起作用,有时候不起作用
            stopwatch.Start();
            RedisCacheHelper.Instance.HashSet<OrderForm>("orderform_hashkey", "orderform_hashfield", getlist.FirstOrDefault(), new TimeSpan(0, 0, 10), 2);
            stopwatch.Stop();
            Console.WriteLine("保存或修改一个hash对象(序列化)消耗时间:" + stopwatch.ElapsedMilliseconds.ToString());

            //保存Hash对象集合 序列化   对key设置过期时间可以起作用
            stopwatch.Start();
            RedisCacheHelper.Instance.HashSet<OrderForm>("orderformlist_hashkey", getlist, m=> { return m.ordercode.ToString(); }, new TimeSpan(0, 0, 30), 3);
            stopwatch.Stop();
            Console.WriteLine("保存Hash对象集合(序列化)消耗时间:" + stopwatch.ElapsedMilliseconds.ToString());

            //从Hash Redis获取某一条订单信息  反序列化
            stopwatch.Start();
            var getorderinfo = RedisCacheHelper.Instance.HashGet<OrderForm>("orderform_hashkey", "orderform_hashfield", 2);
            stopwatch.Stop();
            Console.WriteLine("从Hash Redis获取某一条订单信息消耗时间:" + stopwatch.ElapsedMilliseconds.ToString());
            Console.WriteLine(getorderinfo.ordercode);
            Console.WriteLine(getorderinfo.Area);
            Console.WriteLine(getorderinfo.City);
            Console.WriteLine(getorderinfo.Province);
            Console.WriteLine(getorderinfo.PostTime);

            //根据hashkey 获取所有的值  反序列化
            stopwatch.Start();
            var getorderlist = RedisCacheHelper.Instance.HashGetAll<OrderForm>("orderformlist_hashkey", 3);
            stopwatch.Stop();
            Console.WriteLine("根据hashkey 获取所有的值消耗时间:" + stopwatch.ElapsedMilliseconds.ToString());
            foreach (var item in getorderlist)
            {
                Console.WriteLine("获取反序列化得到的ordercode: " + item.ordercode);
            }

            //根据hashkey获取单个字段hashField的值
            stopwatch.Start();
            var getvalue = RedisCacheHelper.Instance.HashGet("objlist_hashkey1", "City", 1);
            stopwatch.Stop();
            Console.WriteLine("获取单个字段hashField的值消耗时间:" + stopwatch.ElapsedMilliseconds.ToString());
            Console.WriteLine("获取City: " + getvalue);

            Console.WriteLine("------------------");
            Console.WriteLine();

            //获取多个字段hashField的值
            List<RedisValue> fieldlist = new List<RedisValue>() { "ordercode", "Province", "City", "Area" };
            stopwatch.Start();
            var getlist = RedisCacheHelper.Instance.HashGet("objlist_hashkey1", fieldlist.ToArray(), 1);
            stopwatch.Stop();
            Console.WriteLine("获取多个字段hashField的值消耗时间:" + stopwatch.ElapsedMilliseconds.ToString());
            foreach (var item in getlist)
            {
                Console.WriteLine("获取到的值: " + item);
            }

            //根据hashkey返回所有的HashFiled
            stopwatch.Start();
            var getkeylist = RedisCacheHelper.Instance.HashKeys("objlist_hashkey1", 1);
            stopwatch.Stop();
            Console.WriteLine("消耗时间:" + stopwatch.ElapsedMilliseconds.ToString());
            foreach (var item in getkeylist)
            {
                Console.WriteLine("获取到的HashFiled: " + item);
            }

            //根据hashkey返回所有HashFiled值
            stopwatch.Start();
            var getvaluelist = RedisCacheHelper.Instance.HashValues("objlist_hashkey1", 1);
            stopwatch.Stop();
            Console.WriteLine("消耗时间:" + stopwatch.ElapsedMilliseconds.ToString());
            foreach (var item in getvaluelist)
            {
                Console.WriteLine("获取到的HashFiled值: " + item);
            }

这里附上RedisHelp

        /// <summary>
        /// 判断该字段是否存在 hash 中
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="hashField"></param>
        /// <returns></returns>
        public bool HashExists(string redisKey, string hashField, int db = -1)
        {
            try
            {
                _db = GetDatabase(db);
                return _db.HashExists(redisKey, hashField);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 从 hash 中移除指定字段
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="hashField"></param>
        /// <returns></returns>
        public bool HashDelete(string redisKey, string hashField, int db = -1)
        {
            try
            {
                _db = GetDatabase(db);
                return _db.HashDelete(redisKey, hashField);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 从 hash 中移除多个指定字段
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="hashField"></param>
        /// <returns></returns>
        public long HashDelete(string redisKey, IEnumerable<RedisValue> hashField, int db = -1)
        {
            try
            {
                _db = GetDatabase(db);
                return _db.HashDelete(redisKey, hashField.ToArray());
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 递增  默认按1递增  可用于计数
        /// </summary>
        /// <param name="key"></param>
        /// <param name="span"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        public long HashIncrement(string redisKey, string hashField, TimeSpan? span = null, int db = -1)
        {
            try
            {
                _db = GetDatabase(db);
                var result = _db.HashIncrement(redisKey, hashField);
                //设置过期时间
                if (span != null)
                {
                    this.KeyExpire(redisKey, span);
                }
                return result;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 递减  默认按1递减   可用于抢购类的案例
        /// </summary>
        /// <param name="key"></param>
        /// <param name="span"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        public long HashDecrement(string redisKey, string hashField, TimeSpan? span = null, int db = -1)
        {
            try
            {
                _db = GetDatabase(db);
                var result = _db.HashDecrement(redisKey, hashField);
                //设置过期时间
                if (span != null)
                {
                    this.KeyExpire(redisKey, span);
                }
                return result;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 在 hash 中保存或修改一个值   字符类型
        /// set or update the HashValue for string key
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="hashField"></param>
        /// <param name="value"></param>
        /// <param name="span">过期时间,可空</param>
        /// <returns></returns>
        public bool HashSet(string redisKey, string hashField, string value, TimeSpan? span = null, int db = -1)
        {
            try
            {
                _db = GetDatabase(db);
                if (span != null)
                {
                    //设置过期时间
                    this.KeyExpire(redisKey, span);
                }
                return _db.HashSet(redisKey, hashField, value);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 保存一个字符串类型集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="redisKey">Redis Key</param>
        /// <param name="list">数据集合</param>
        /// <param name="getFiledKey">字段key</param>
        public void HashSetList(string redisKey, IEnumerable<string> list, Func<string, string> getFiledKey, TimeSpan? span = null, int db = -1)
        {
            try
            {
                _db = GetDatabase(db);
                List<HashEntry> listHashEntry = new List<HashEntry>();
                foreach (var item in list)
                {
                    listHashEntry.Add(new HashEntry(getFiledKey(item), item));
                }
                _db.HashSet(redisKey, listHashEntry.ToArray());

                if (span != null)
                {
                    //设置过期时间
                    this.KeyExpire(redisKey, span);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 保存多个对象集合  非序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tableName">表名前缀</param>
        /// <param name="list">数据集合</param>
        /// <param name="getModelId">字段key</param>
        public void HashSetObjectList<T>(string tableName, IEnumerable<T> list, Func<T, string> getModelId, int db = -1) where T : class
        {
            try
            {
                _db = GetDatabase(db);
                foreach (var item in list)
                {
                    List<HashEntry> listHashEntry = new List<HashEntry>();
                    Type t = item.GetType();//获得该类的Type
                    foreach (PropertyInfo pi in t.GetProperties())
                    {
                        string name = pi.Name; //获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作
                        var value = pi.GetValue(item, null);  //用pi.GetValue获得值
                        listHashEntry.Add(new HashEntry(name, value.ToString()));
                    }
                    _db.HashSet(tableName + getModelId(item), listHashEntry.ToArray());
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 保存或修改一个hash对象(序列化)
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="hashField"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool HashSet<T>(string redisKey, string hashField, T value, TimeSpan? span = null, int db = -1) where T : class
        {
            try
            {
                _db = GetDatabase(db);
                var json = JsonConvert.SerializeObject(value);
                if (span != null)
                {
                    //设置过期时间
                    this.KeyExpire(redisKey, span);
                }
                return _db.HashSet(redisKey, hashField, json);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 保存Hash对象集合 序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="redisKey">Redis Key</param>
        /// <param name="list">数据集合</param>
        /// <param name="getModelId"></param>
        public void HashSet<T>(string redisKey, IEnumerable<T> list, Func<T, string> getModelId, TimeSpan? span = null, int db = -1) where T : class
        {
            try
            {
                _db = GetDatabase(db);
                List<HashEntry> listHashEntry = new List<HashEntry>();
                foreach (var item in list)
                {
                    string json = JsonConvert.SerializeObject(item);
                    listHashEntry.Add(new HashEntry(getModelId(item), json));
                }
                _db.HashSet(redisKey, listHashEntry.ToArray());

                if (span != null)
                {
                    //设置过期时间
                    this.KeyExpire(redisKey, span);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 从 hash 中获取对象(反序列化)
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="hashField"></param>
        /// <returns></returns>
        public T HashGet<T>(string redisKey, string hashField, int db = -1) where T : class
        {
            try
            {
                _db = GetDatabase(db);
                return JsonConvert.DeserializeObject<T>(_db.HashGet(redisKey, hashField));
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        ///  根据hashkey获取所有的值  序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="redisKey"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        public List<T> HashGetAll<T>(string redisKey, int db = -1) where T : class
        {
            List<T> result = new List<T>();
            try
            {
                _db = GetDatabase(db);
                HashEntry[] arr = _db.HashGetAll(redisKey);
                foreach (var item in arr)
                {
                    if (!item.Value.IsNullOrEmpty)
                    {
                        var t = JsonConvert.DeserializeObject<T>(item.Value);
                        if (t != null)
                        {
                            result.Add(t);
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            return result;
        }

        /// <summary>
        ///  根据hashkey获取所有的值  非序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="redisKey"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        public IEnumerable<Dictionary<RedisValue, RedisValue>> HashGetAll(IEnumerable<string> redisKey, int db = -1)
        {
            List<Dictionary<RedisValue, RedisValue>> diclist = new List<Dictionary<RedisValue, RedisValue>>();
            try
            {
                _db = GetDatabase(db);
                foreach (var item in redisKey)
                {
                    HashEntry[] arr = _db.HashGetAll(item);
                    foreach (var he in arr)
                    {
                        Dictionary<RedisValue, RedisValue> dic = new Dictionary<RedisValue, RedisValue>();
                        if (!he.Value.IsNullOrEmpty)
                        {
                            dic.Add(he.Name, he.Value);
                        }
                        diclist.Add(dic);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            return diclist;
        }

        /// <summary>
        /// 根据hashkey获取单个字段hashField的值
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="hashField"></param>
        /// <returns></returns>
        public RedisValue HashGet(string redisKey, string hashField, int db = -1)
        {
            try
            {
                _db = GetDatabase(db);
                return _db.HashGet(redisKey, hashField);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 根据hashkey获取多个字段hashField的值
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="hashField"></param>
        /// <returns></returns>
        public RedisValue[] HashGet(string redisKey, RedisValue[] hashField, int db = -1)
        {
            _db = GetDatabase(db);
            return _db.HashGet(redisKey, hashField);
        }

        /// <summary>
        /// 根据hashkey返回所有的HashFiled
        /// </summary>
        /// <param name="redisKey"></param>
        /// <returns></returns>
        public IEnumerable<RedisValue> HashKeys(string redisKey, int db = -1)
        {
            _db = GetDatabase(db);
            return _db.HashKeys(redisKey);
        }

        /// <summary>
        /// 根据hashkey返回所有HashValue值
        /// </summary>
        /// <param name="redisKey"></param>
        /// <returns></returns>
        public RedisValue[] HashValues(string redisKey, int db = -1)
        {
            _db = GetDatabase(db);
            return _db.HashValues(redisKey);
        }

原文地址:https://www.cnblogs.com/peterzhang123/p/12310384.html

时间: 2024-10-10 12:50:28

StackExchange.Redis 之 hash 类型示例的相关文章

StackExchange.Redis 之 String 类型示例

String类型很简单,就不做示例演示了,这里只贴出Helper类 /// <summary> /// 判断key是否存在 /// </summary> /// <param name="key"></param> /// <param name="db"></param> /// <returns></returns> public bool KeyExists(str

二:redis 的hash类型相关操作

=====================二种:hash类型================== 介绍:redis -> hash是一个string类型的field和value的映射表 hash特别适合对应存储对象,相较于将对象的每个字段存成单个string类型 将一个对象存储在hash类型中会占用更少的内存,并且可以方便的存取整个对象 0:hset *如果 key(就是hash表) 不存在,一个新的哈希表被创建并进行 HSET 操作 设置hash field为指定值,如果key不存在,则先创建

怎样在Redis通过StackExchange.Redis 存储集合类型List

StackExchange 是由StackOverFlow出品, 是对Redis的.NET封装,被越来越多的.NET开发者使用在项目中. 绝大部分原先使用ServiceStack的开发者逐渐都转了过来,由于SS在其新版中不再开源,并对免费版本有所限制. 实际问题 那么用.NET的开发者会发现,其根本没有对List类型的存储封装,那么要实现一个类似如下需求:假如我有一个Customer的模型. public class Customer { public string FirstName { ge

33. Python redis的 hash类型操作 其他常用操作

1.hash 类型操作 import redis pool = redis.ConnectionPool(host="192.168.48.131", port=6379, db=0) r = redis.Redis(connection_pool=pool) #hash类型操作:是一个name对应一个字典 #语法 hset(name, key, value) #name 对应的hash中设置一个键值对(不存在,则创建键值对:否则,修改键值对) # 语法参数解释: name: redi

Redis之-hash类型

hash数据类型的相关命令1,hset命令127.0.0.1:6379> hset user name yuhao(integer) 1127.0.0.1:6379> hset user age 19(integer) 1127.0.0.1:6379> hset user from qinghai(integer) 1127.0.0.1:6379> hgetall user1) "name"2) "yuhao"3) "age&quo

Windows下Redis缓存服务器的使用 .NET StackExchange.Redis Redis Desktop Manager

Redis缓存服务器是一款key/value数据库,读110000次/s,写81000次/s,因为是内存操作所以速度飞快,常见用法是存用户token.短信验证码等 官网显示Redis本身并没有Windows版本的,微软官方开发了基于Windows的Redis服务器:MSOpenTech/redis 一.Redis服务端 首先下载Redis服务器,点击前往下载.msi版本,双击安装Redis服务端就有了,并以服务的形式随系统一起启动: 安装好Redis服务器之后第一件事就是设置密码,进入安装目录:

Redis 笔记与总结2 String 类型和 Hash 类型

Linux 版本信息: cat /etc/issue 或cat /etc/redhat-release(Linux查看版本当前操作系统发行版信息) CentOS release 6.6 (Final) (一)String 类型 [定义]string 是最简单的类型,你可以理解成与 Memcached 是一模一样的类型,一个 key 对应一个 value,其上支持的操作与 Memcached 的操作类似.但它的功能更丰富. string 类型是二进制安全的.意思是 redis 的 string 可

Redis数据类型之HASH类型

Web程序猿博客:http://blog.csdn.net/thinkercode HASH类型-特点 Redis hash 是一个 string 类型的 field 和 value 的映射表.它的添加. 删除操作都是 O(1) (平均) . hash 特别适合用于存储对象. 相较于将对象的每个字段存成单个 string 类型. 将一个对象存储在 hash 类型中会占用更少的内存,并且可以更方便的存取整个对象.省内存的原因是新建一个 hash 对象时开始是用 zipmap(又称为 small h

[redis数据结构]之 hash类型

在讲解语法知识之前,教你如何掌握各种hash的基本潜规则,在不同的语言中,有点称之为hash.有的是map,但不管这么样,hash你可以看作是key-value一组的集合.我先将java中map的概念擅自的加入到redis的hash中,让我们更加容易的理解hash的潜规则: 一.hash潜规则 1.映射模型 值集合映射,键集合映射,Entry集合映射(key-value,有得称之为item(python)). 2.一般的方法列表 添加.删除.更新.判断键是否存在.对应映射模型的key集合.val