码迷,mamicode.com
首页 > 其他好文 > 详细

StackExchange.Redis 之 hash 类型示例

时间:2020-02-16 14:31:20      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:cti   案例   字符   summary   指定字段   ram   get   字符串   stop   

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);
        }
View Code

StackExchange.Redis 之 hash 类型示例

标签:cti   案例   字符   summary   指定字段   ram   get   字符串   stop   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!