1 module RedisLockDemo; 2 3 import hunt.redis; 4 5 import hunt.logging.ConsoleLogger; 6 7 import core.thread; 8 import std.stdio; 9 import std.conv; 10 11 // string RedisHosts = "10.1.11.115:6379;10.1.11.115:6380;10.1.11.115:6381;10.1.11.115:7000;10.1.11.115:7001;10.1.11.115:7002"; 12 // string RedisHosts = "10.1.23.222:6379"; 13 14 void run() 15 { 16 17 TestThread[] list; 18 for (uint i = 0; i < 10; i++) 19 { 20 auto test = new TestThread("client " ~ to!string(i), 1); 21 test.start(); 22 list ~= test; 23 } 24 25 Thread.sleep(dur!"seconds"(5)); 26 27 foreach (t; list) 28 { 29 t.stop(); 30 } 31 32 int i = 0; 33 i++; 34 // foreach (t; list) 35 // t.join(); 36 37 } 38 39 class TestThread : Thread 40 { 41 string _name; 42 int _second; 43 bool _flag; 44 RedisLock _lock; 45 Redis _redis; 46 47 this(string name, int second) 48 { 49 super(&run); 50 _name = name; 51 _second = second; 52 _redis = new Redis("10.1.23.222", 6379); 53 _redis.auth("foobared"); 54 _lock = new RedisLock(_redis, "test1"); 55 _flag = true; 56 } 57 58 void stop() 59 { 60 if(_flag) { 61 _flag = false; 62 _redis.close(); 63 } 64 } 65 66 void run() 67 { 68 while (_flag) 69 { 70 if (!_lock.lock(1000)) 71 { 72 warningf(" timeout: %s ", _name); 73 continue; 74 } 75 76 info(_name, " locked"); 77 Thread.sleep(dur!"msecs"(500)); 78 info(_name, " unlocked"); 79 _lock.unlock(); 80 Thread.sleep(dur!"seconds"(1)); 81 } 82 83 } 84 }