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_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 ("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_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("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的值 Listfieldlist = new List () { "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); }
//模拟并发场景 使用HashDecrement递减功能 使用分布式锁,但是线程线程排队处理,有可能照成Redis超时
该示例会照成1个用户抢多个
stopwatch.Start(); ListtaskList = new List (); for (int i = 1; i <= 100; i++) //模拟多个用户同时请求 { var task = Task.Run(() => { try { //*************************开始**************** RedisValue token = Environment.MachineName; while (true) { if (RedisCacheHelper.Instance.LockAndDo("lock_key", token, () => { //在这里处理并发逻辑 //先获取库存数 var getvalues = (int)RedisCacheHelper.Instance.HashGet("order_hashkey", "order_hashfield"); if (getvalues > 0) { //先自减,获取自减后的值 int order_Num = (int)RedisCacheHelper.Instance.HashDecrement("order_hashkey", "order_hashfield", null); if (order_Num >= 0) { //下面执行订单逻辑(这里不考虑业务出错的情况) Console.WriteLine("我抢到了,还剩余数量:" + order_Num); } else { Console.WriteLine("A商品已经被抢光了"); } return true; } else { Console.WriteLine("B商品已经被抢光了"); return true; } }, new TimeSpan(0, 0, 10))) { break; } } } catch (Exception ex) { Console.WriteLine(ex.Message); throw; } }); taskList.Add(task); } Task.WaitAll(taskList.ToArray()); stopwatch.Stop(); Console.WriteLine("模拟并发场景消耗时间:" + stopwatch.ElapsedMilliseconds.ToString());
抢购前库存30个
抢购后库存0
这里附上RedisHelp
////// 判断该字段是否存在 hash 中 /// /// /// /// public bool HashExists(string redisKey, string hashField, int db = -1) { try { _db = GetDatabase(db); return _db.HashExists(redisKey, hashField); } catch (Exception) { throw; } } /// /// 从 hash 中移除指定字段 /// /// /// /// public bool HashDelete(string redisKey, string hashField, int db = -1) { try { _db = GetDatabase(db); return _db.HashDelete(redisKey, hashField); } catch (Exception) { throw; } } /// /// 从 hash 中移除多个指定字段 /// /// /// /// public long HashDelete(string redisKey, IEnumerable hashField, int db = -1) { try { _db = GetDatabase(db); return _db.HashDelete(redisKey, hashField.ToArray()); } catch (Exception) { throw; } } /// /// 递增 默认按1递增 可用于计数 /// /// /// /// /// 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; } } /// /// 递减 默认按1递减 可用于抢购类的案例 /// /// /// /// /// 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; } } /// /// 在 hash 中保存或修改一个值 字符类型 /// set or update the HashValue for string key /// /// /// /// /// 过期时间,可空 /// 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; } } /// /// 保存一个字符串类型集合 /// /// /// Redis Key /// 数据集合 /// 字段key public void HashSetList(string redisKey, IEnumerable<string> list, Func<string, string> getFiledKey, TimeSpan? span = null, int db = -1) { try { _db = GetDatabase(db); List listHashEntry = new List (); 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; } } /// /// 保存多个对象集合 非序列化 /// /// /// 表名前缀 /// 数据集合 /// 字段key public void HashSetObjectList (string tableName, IEnumerable list, Func string> getModelId, int db = -1) where T : class { try { _db = GetDatabase(db); foreach (var item in list) { List listHashEntry = new List (); 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; } } /// /// 保存或修改一个hash对象(序列化) /// /// /// /// /// public bool HashSet (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; } } /// /// 保存Hash对象集合 序列化 /// /// /// Redis Key /// 数据集合 /// public void HashSet (string redisKey, IEnumerable list, Func string> getModelId, TimeSpan? span = null, int db = -1) where T : class { try { _db = GetDatabase(db); List listHashEntry = new List (); 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; } } /// /// 从 hash 中获取对象(反序列化) /// /// /// /// public T HashGet (string redisKey, string hashField, int db = -1) where T : class { try { _db = GetDatabase(db); return JsonConvert.DeserializeObject (_db.HashGet(redisKey, hashField)); } catch (Exception) { throw; } } /// /// 根据hashkey获取所有的值 序列化 /// /// /// /// /// public List HashGetAll (string redisKey, int db = -1) where T : class { List result = new List (); try { _db = GetDatabase(db); HashEntry[] arr = _db.HashGetAll(redisKey); foreach (var item in arr) { if (!item.Value.IsNullOrEmpty) { var t = JsonConvert.DeserializeObject (item.Value); if (t != null) { result.Add(t); } } } } catch (Exception) { throw; } return result; } /// /// 根据hashkey获取所有的值 非序列化 /// /// /// /// /// public IEnumerable > HashGetAll(IEnumerable<string> redisKey, int db = -1) { List > diclist = new List >(); try { _db = GetDatabase(db); foreach (var item in redisKey) { HashEntry[] arr = _db.HashGetAll(item); foreach (var he in arr) { Dictionary dic = new Dictionary (); if (!he.Value.IsNullOrEmpty) { dic.Add(he.Name, he.Value); } diclist.Add(dic); } } } catch (Exception) { throw; } return diclist; } /// /// 根据hashkey获取单个字段hashField的值 /// /// /// /// public RedisValue HashGet(string redisKey, string hashField, int db = -1) { try { _db = GetDatabase(db); return _db.HashGet(redisKey, hashField); } catch (Exception) { throw; } } /// /// 根据hashkey获取多个字段hashField的值 /// /// /// /// public RedisValue[] HashGet(string redisKey, RedisValue[] hashField, int db = -1) { _db = GetDatabase(db); return _db.HashGet(redisKey, hashField); } /// /// 根据hashkey返回所有的HashFiled /// /// /// public IEnumerable HashKeys(string redisKey, int db = -1) { _db = GetDatabase(db); return _db.HashKeys(redisKey); } /// /// 根据hashkey返回所有HashValue值 /// /// /// public RedisValue[] HashValues(string redisKey, int db = -1) { _db = GetDatabase(db); return _db.HashValues(redisKey); }