public void SimulateLockTimeout() { var redisClient = new RedisClient(Config.MasterHost); var waitFor = TimeSpan.FromMilliseconds(20); var loc = redisClient.AcquireLock("testlock", waitFor); Thread.Sleep(100); // should have lock expire using (var newloc = redisClient.AcquireLock("testlock", waitFor)) { } }
public void Set(string key, string value, ulong cas) { using (var casLock = Client.AcquireLock(key + lockSuffix, TimeSpan.FromSeconds(10))) { var casDB = Client.Get <ulong>(key + casSuffix); if (casDB != cas) { throw new CASException("CAS values do not match"); } Client.Set(key, Encoding.UTF8.GetBytes(value)); GetNextSequenceValue(key + casSuffix, 1); } }
public void AcquireLock_using_Tasks() { const int noOfClients = 4; var tasks = new Task[noOfClients]; for (var i = 0; i < noOfClients; i++) { Thread.Sleep(2000); tasks[i] = Task.Factory.StartNew((object clientNo) => { try { Console.WriteLine("About to process " + clientNo); //var redisClient = new RedisClient("xxxx.redis.cache.windows.net", 6379, "xxxx"); var redisClient = new RedisClient(TestConfig.SingleHost, 6379); using (redisClient.AcquireLock("testlock1", TimeSpan.FromMinutes(3))) { Console.WriteLine("client {0} acquired lock", (int)clientNo); var counter = redisClient.Get <int>("atomic-counter"); //Add an artificial delay to demonstrate locking behaviour Thread.Sleep(100); redisClient.Set("atomic-counter", counter + 1); Console.WriteLine("client {0} released lock", (int)clientNo); } } catch (Exception e) { Console.WriteLine(e.Message); } }, i + 1); } }
public void Acquiring_lock_with_timeout() { var redisClient = new RedisClient(TestConfig.SingleHost); //Initialize and set counter to '1' redisClient.IncrementValue("atomic-counter"); //Acquire lock and never release it redisClient.AcquireLock("testlock"); var waitFor = TimeSpan.FromSeconds(2); var now = DateTime.Now; try { using (var newClient = new RedisClient(TestConfig.SingleHost)) { //Attempt to acquire a lock with a 2 second timeout using (newClient.AcquireLock("testlock", waitFor)) { //If lock was acquired this would be incremented to '2' redisClient.IncrementValue("atomic-counter"); } } } catch (TimeoutException tex) { var timeTaken = DateTime.Now - now; Debug.WriteLine(String.Format("After '{0}', Received TimeoutException: '{1}'", timeTaken, tex.Message)); var counter = redisClient.Get <int>("atomic-counter"); Debug.WriteLine(String.Format("atomic-counter remains at '{0}'", counter)); } }
public void Can_AcquireLock_TimeOut() { Redis.IncrementValue("key"); //1 var acquiredLock = Redis.AcquireLock("testlock"); var waitFor = TimeSpan.FromMilliseconds(1000); var now = DateTime.Now; try { using (var client = new RedisClient(TestConfig.SingleHost)) { using (client.AcquireLock("testlock", waitFor)) { Redis.IncrementValue("key"); //2 } } } catch (TimeoutException tex) { var val = Redis.Get <int>("key"); Assert.That(val, Is.EqualTo(1)); var timeTaken = DateTime.Now - now; Assert.That(timeTaken.TotalMilliseconds > waitFor.TotalMilliseconds, Is.True); Assert.That(timeTaken.TotalMilliseconds < waitFor.TotalMilliseconds + 1000, Is.True); return; } Assert.Fail("should have Timed out"); }
public void Can_AcquireLock_Timeout() { var key = this.PrefixedKey("AcquireLockKeyTimeout"); var lockKey = this.PrefixedKey("Can_AcquireLock_Timeout"); this.Redis.IncrementValue(key); // 1 using (var acquiredLock = this.Redis.AcquireLock(lockKey)) { var waitFor = TimeSpan.FromMilliseconds(1000); var now = DateTime.Now; try { using (var client = new RedisClient(Config.MasterHost)) { using (client.AcquireLock(lockKey, waitFor)) { this.Redis.IncrementValue(key); // 2 } } } catch (TimeoutException) { var val = this.Redis.Get <int>(key); Assert.That(val, Is.EqualTo(1)); var timeTaken = DateTime.Now - now; Assert.That(timeTaken.TotalMilliseconds > waitFor.TotalMilliseconds, Is.True); Assert.That(timeTaken.TotalMilliseconds < waitFor.TotalMilliseconds + 1000, Is.True); return; } } Assert.Fail("should have Timed out"); }
public void Acquiring_lock_with_timeout() { var redisClient = new RedisClient(TestConfig.SingleHost); //Initialize and set counter to '1' redisClient.IncrementValue("atomic-counter"); //Acquire lock and never release it redisClient.AcquireLock("testlock"); var waitFor = TimeSpan.FromSeconds(2); var now = DateTime.Now; try { using (var newClient = new RedisClient(TestConfig.SingleHost)) { //Attempt to acquire a lock with a 2 second timeout using (newClient.AcquireLock("testlock", waitFor)) { //If lock was acquired this would be incremented to '2' redisClient.IncrementValue("atomic-counter"); } } } catch (TimeoutException tex) { var timeTaken = DateTime.Now - now; Debug.WriteLine(String.Format("After '{0}', Received TimeoutException: '{1}'", timeTaken, tex.Message)); var counter = redisClient.Get<int>("atomic-counter"); Debug.WriteLine(String.Format("atomic-counter remains at '{0}'", counter)); } }
private void button45_Click(object sender, EventArgs e) { client.Set("lock", 1); using (client.AcquireLock("lock")) { client.Set("lock", 2); } textBox1.Text = client.Get<int>("lock").ToString(); }
//这个是阻塞的锁 public static void Show(int i, string key, TimeSpan timeout) { using (var client = new RedisClient("127.0.0.1", 6379, "123456")) { //只是加了这么一句话 // 如果有一个先进去了,写入了key:DataLock+key。它执行完需要200毫秒 // 同时来了三个线程,他们发现 key里面有值了,循环等待,什么时候,key里面没有值,然后自己可以执行代码 // 用到了微循环,那必然要给一个限制 //timeout 这个参数的意义,我最多等待这么长时间,如果拿不到,则我不需要在等待了 //所以我们设置这个时间的时候,要合理一些 // 这个时间还有一个意义 // 表示,当前拿到锁进去的这个线程,最多能活多久,这个锁的存活的时间 //规定时间,还没出来,就把锁释放掉 //他没循环完,就是释放了锁。。 // 加了这句话,下面所有的代码都是单线程的执行 using (var datalock = client.AcquireLock("DataLock:" + key, timeout)) { //库存数量 var inventory = client.Get <int>("inventoryNum"); if (inventory > 0) { client.Set <int>("inventoryNum", inventory - 1); //订单数量 var orderNum = client.Incr("orderNum"); Console.WriteLine($"{i}抢购成功*****线程id:{ Thread.CurrentThread.ManagedThreadId.ToString("00")},库存:{inventory},订单数量:{orderNum}"); } else { Console.WriteLine($"{i}抢购失败"); } //client.Remove("DataLock:" + key); Thread.Sleep(300); } } }
public void Use_multiple_redis_clients_to_safely_execute() { //The number of concurrent clients to run const int noOfClients = 5; var asyncResults = new List <IAsyncResult>(noOfClients); for (var i = 1; i <= noOfClients; i++) { var clientNo = i; var actionFn = (Action) delegate { var redisClient = new RedisClient(TestConfig.SingleHost); using (redisClient.AcquireLock("testlock")) { Debug.WriteLine(String.Format("client {0} acquired lock", clientNo)); var counter = redisClient.Get <int>("atomic-counter"); //Add an artificial delay to demonstrate locking behaviour Thread.Sleep(100); redisClient.Set("atomic-counter", counter + 1); Debug.WriteLine(String.Format("client {0} released lock", clientNo)); } }; //Asynchronously invoke the above delegate in a background thread asyncResults.Add(actionFn.BeginInvoke(null, null)); } //Wait at most 1 second for all the threads to complete asyncResults.WaitAll(TimeSpan.FromSeconds(1)); //Print out the 'atomic-counter' result using (var redisClient = new RedisClient(TestConfig.SingleHost)) { var counter = redisClient.Get <int>("atomic-counter"); Debug.WriteLine(String.Format("atomic-counter after 1sec: {0}", counter)); } }
public void Use_multiple_redis_clients_to_safely_execute() { //The number of concurrent clients to run const int noOfClients = 5; var asyncResults = new List<IAsyncResult>(noOfClients); for (var i = 1; i <= noOfClients; i++) { var clientNo = i; var actionFn = (Action)delegate { var redisClient = new RedisClient(TestConfig.SingleHost); using (redisClient.AcquireLock("testlock")) { Debug.WriteLine(String.Format("client {0} acquired lock", clientNo)); var counter = redisClient.Get<int>("atomic-counter"); //Add an artificial delay to demonstrate locking behaviour Thread.Sleep(100); redisClient.Set("atomic-counter", counter + 1); Debug.WriteLine(String.Format("client {0} released lock", clientNo)); } }; //Asynchronously invoke the above delegate in a background thread asyncResults.Add(actionFn.BeginInvoke(null, null)); } //Wait at most 1 second for all the threads to complete asyncResults.WaitAll(TimeSpan.FromSeconds(1)); //Print out the 'atomic-counter' result using (var redisClient = new RedisClient(TestConfig.SingleHost)) { var counter = redisClient.Get<int>("atomic-counter"); Debug.WriteLine(String.Format("atomic-counter after 1sec: {0}", counter)); } }
public void Can_AcquireLock_TimeOut() { // guid here is to prevent competition between concurrent runtime tests var key = PrefixedKey("AcquireLockKeyTimeOut:" + Guid.NewGuid()); var lockKey = PrefixedKey("Can_AcquireLock_TimeOut:" + Guid.NewGuid()); Redis.IncrementValue(key); //1 var acquiredLock = Redis.AcquireLock(lockKey); var waitFor = TimeSpan.FromMilliseconds(1000); var now = DateTime.Now; try { using (var client = new RedisClient(TestConfig.SingleHost)) { using (client.AcquireLock(lockKey, waitFor)) { Redis.IncrementValue(key); //2 } } } catch (TimeoutException) { var val = Redis.Get <int>(key); Assert.That(val, Is.EqualTo(1)); var timeTaken = DateTime.Now - now; Assert.That(timeTaken.TotalMilliseconds > waitFor.TotalMilliseconds, Is.True); Assert.That(timeTaken.TotalMilliseconds < waitFor.TotalMilliseconds + 3000, Is.True); return; } finally { Redis.Remove(key); Redis.Remove(lockKey); } Assert.Fail("should have Timed out"); }
public void Use_multiple_redis_clients_to_safely_execute() { // The number of concurrent clients to run const int noOfClients = 5; var asyncResults = new List <Task>(noOfClients); for (var i = 1; i <= noOfClients; i++) { var clientNo = i; // Asynchronously var item = Task.Run(() => { var redisClient = new RedisClient(Config.MasterHost); using (redisClient.AcquireLock("testlock")) { Console.WriteLine("client {0} acquired lock", clientNo); var counter = redisClient.Get <int>("atomic-counter"); // Add an artificial delay to demonstrate locking behaviour Thread.Sleep(100); redisClient.Set("atomic-counter", counter + 1); Console.WriteLine("client {0} released lock", clientNo); } }); asyncResults.Add(item); } // Wait at most 1 second for all the threads to complete Task.WaitAll(asyncResults.ToArray(), TimeSpan.FromSeconds(1)); // Print out the 'atomic-counter' result using (var redisClient = new RedisClient(Config.MasterHost)) { var counter = redisClient.Get <int>("atomic-counter"); Console.WriteLine("atomic-counter after 1sec: {0}", counter); } }
//这个是阻塞的锁 public static void Show(int i, string key, TimeSpan timeout) { using (var client = new RedisClient("127.0.0.1", 6379)) { //获取锁 using (var datalock = client.AcquireLock("DataLock:" + key, timeout)) { //库存数量 var inventory = client.Get <int>("inventoryNum"); if (inventory > 0) { client.Set <int>("inventoryNum", inventory - 1); //订单数量 var orderNum = client.Incr("order Num"); WriteLine($"{i}抢购成功xx线程ID:{Thread.CurrentThread.ManagedThreadId.ToString("00")},库存数量:{inventory},订单数量:{orderNum}"); } else { WriteLine($"{i}抢购失败"); } Thread.Sleep(100); } }; }
public void SimulateLockTimeout() { var redisClient = new RedisClient(TestConfig.SingleHost); var waitFor = TimeSpan.FromMilliseconds(20); var loc = redisClient.AcquireLock("testlock",waitFor); Thread.Sleep(100); //should have lock expire using(var newloc = redisClient.AcquireLock("testlock", waitFor)) { } }
public void SecondKill(string id, int minute) { rc.Set <long>("number", 10); Console.WriteLine($"在{minute}分0秒进行秒杀开始!"); #region 秒杀Temple1 var flag = true; string key = "skey"; TimeSpan timeout = TimeSpan.FromSeconds(100); while (flag) { if (DateTime.Now.Minute == minute) { flag = false; for (int i = 0; i < 100; i++) { string name = $"客户端ID{id}号:{i}"; Task.Run(() => { //获取锁 timeout 不是过期时间 using (var dataLock = rc.AcquireLock("DataLock:" + key, timeout)) { long num = rc.Decr("number");//减库存1 rc.Incr("number");//加一 if (num < 0) { Console.WriteLine($"{name}抢购失败!"); } else { Console.WriteLine($"{name}*************抢购成功!***********"); } rc.Remove("DataLock:" + key);//释放锁 } }); Thread.Sleep(10); } } #endregion #region 秒杀 temple2 //var flag = true; //while (flag) //{ // if (DateTime.Now.Minute == minute) // { // flag = false; // for (int i = 0; i < 100; i++) // { // string name = $"客户端ID{id}号:{i}"; // Add(name); // //Task.Factory.StartNew(()=> { // // OrderInfo mod = new OrderInfo() // // { // // Name = name, // // OrderTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") // // }; // // Console.WriteLine($"{name}下单成功!"); // // string listKey = "orderlist"; // // rc.AddItemToList(listKey, JsonConvert.SerializeObject(mod)); // //}); // //Task.Run(() => // //{ // // OrderInfo mod = new OrderInfo() // // { // // Name = name, // // OrderTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") // // }; // // Console.WriteLine($"{name}下单成功!"); // // string listKey = "orderlist"; // // rc.AddItemToList(listKey, JsonConvert.SerializeObject(mod)); // //}); // // Thread.Sleep(10); // } // } #endregion } }
public IDisposable AcquireLock() { return(client.AcquireLock(this.TypeLockKey)); }
public void Can_AcquireLock_TimeOut() { var key = PrefixedKey("AcquireLockKeyTimeOut"); var lockKey = PrefixedKey("Can_AcquireLock_TimeOut"); Redis.IncrementValue(key); //1 var acquiredLock = Redis.AcquireLock(lockKey); var waitFor = TimeSpan.FromMilliseconds(1000); var now = DateTime.Now; try { using (var client = new RedisClient(TestConfig.SingleHost)) { using (client.AcquireLock(lockKey, waitFor)) { Redis.IncrementValue(key); //2 } } } catch (TimeoutException tex) { var val = Redis.Get<int>(key); Assert.That(val, Is.EqualTo(1)); var timeTaken = DateTime.Now - now; Assert.That(timeTaken.TotalMilliseconds > waitFor.TotalMilliseconds, Is.True); Assert.That(timeTaken.TotalMilliseconds < waitFor.TotalMilliseconds + 1000, Is.True); return; } Assert.Fail("should have Timed out"); }
public void AcquireLock_using_Tasks() { const int noOfClients = 4; var tasks = new Task[noOfClients]; for (var i = 0; i < noOfClients; i++) { Thread.Sleep(2000); tasks[i] = Task.Factory.StartNew((object clientNo) => { try { Console.WriteLine("About to process " + clientNo); //var redisClient = new RedisClient("xxxx.redis.cache.windows.net", 6379, "xxxx"); var redisClient = new RedisClient(TestConfig.SingleHost, 6379); using (redisClient.AcquireLock("testlock1", TimeSpan.FromMinutes(3))) { Console.WriteLine("client {0} acquired lock", (int)clientNo); var counter = redisClient.Get<int>("atomic-counter"); //Add an artificial delay to demonstrate locking behaviour Thread.Sleep(100); redisClient.Set("atomic-counter", counter + 1); Console.WriteLine("client {0} released lock", (int)clientNo); } } catch (Exception e) { Console.WriteLine(e.Message); } }, i + 1); } }
public IDisposable AcquireLock(string key) { return(redisClient.AcquireLock(key)); }