/// <summary> /// 添加购物车 /// </summary> /// <param name="OpenId">用户主键</param> /// <param name="Menu_Id"></param> /// <returns></returns> public int AddCar(string OpenId, int Menu_Id) { tb_Menu model = menuList.Where(s => s.M_Id == Menu_Id).FirstOrDefault(); //获取该用户的购物车缓存 List <tb_Menu> _menuList = _client.Get <List <tb_Menu> >(OpenId); if (_menuList != null) { tb_Menu m = _menuList.Where(s => s.M_Id == Menu_Id).FirstOrDefault(); if (m != null) { model.CarNum += 1; } else { model.CarNum = 1; _menuList.Add(model); } } else { _menuList = new List <tb_Menu>(); model.CarNum = 1; _menuList.Add(model); } _client.Set(OpenId, _menuList); return(_menuList.Count); }
static void Main(string[] args) { CSRedisClient redisClient = new CSRedis.CSRedisClient("127.0.0.1:6379,defaultDatabase=0"); var lockKey = "lockKey"; var stockKey = "stock"; redisClient.Set(stockKey, 5); //商品库存 var releaseLockScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; //释放锁的redis脚本 redisClient.Del(lockKey); //测试前,先把锁删了. Parallel.For(0, 10, i => { var id = Guid.NewGuid().ToString("N"); //获取锁 do { //set : key存在则失败,不存在才会成功,并且过期时间5秒 var success = redisClient.Set(lockKey, id, expireSeconds: 5, exists: RedisExistence.Nx); if (success == true) { break; } Thread.Sleep(TimeSpan.FromSeconds(1));//休息1秒再尝试获取锁 } while (true); Console.WriteLine($"线程:{Task.CurrentId} 拿到了锁,开始消费"); //扣减库存 var currentStock = redisClient.IncrBy(stockKey, -1); if (currentStock < 0) { Console.WriteLine($"库存不足,线程:{Task.CurrentId} 抢购失败!"); redisClient.Eval(releaseLockScript, lockKey, id); return; } //模拟处理业务,这里不考虑失败的情况 Thread.Sleep(TimeSpan.FromSeconds(new Random().Next(1, 3))); Console.WriteLine($"线程:{Task.CurrentId} 消费完毕!剩余 {currentStock} 个"); //业务处理完后,释放锁. redisClient.Eval(releaseLockScript, lockKey, id); }); }
public void SentinelInit() { var csredis = new CSRedis.CSRedisClient("mymaster,password=123", new[] { "192.169.1.10:26379", "192.169.1.11:26379", "192.169.1.12:26379" }); csredis.Set("test", DateTime.Now.ToString()); csredis.Get("test"); }
public void ClusterDbInit() { var csredis = new CSRedis.CSRedisClient(null, "127.0.0.1:6371,password=123,defaultDatabase=11,poolsize=10,ssl=false,writeBuffer=10240", "127.0.0.1:6372,password=123,defaultDatabase=12,poolsize=11,ssl=false,writeBuffer=10240", "127.0.0.1:6373,password=123,defaultDatabase=13,poolsize=12,ssl=false,writeBuffer=10240", "127.0.0.1:6374,password=123,defaultDatabase=14,poolsize=13,ssl=false,writeBuffer=10240"); csredis.Set("test", DateTime.Now.ToString()); csredis.Get("test"); }
public void set(string key, string vaue, int senconds = -1) { _redis.Set(key, vaue, senconds); }