From e69bf15cdc3159fbf807a5f9abf8767c519326bd Mon Sep 17 00:00:00 2001 From: huangyg11 Date: Fri, 13 Mar 2015 19:17:49 +0800 Subject: [PATCH 1/2] fix retry meaning. 1. the origin retrycount variable is not exactly stand for retry times. Take retrycount = 1 for example. That means I want try 2 times. But the origin only try one times. 2. When it is the last try, it should not wait retrydelay to return. 3. retrydelay, and retry times should be changable in each lock. --- src/RedLock.php | 25 ++++++++++--------------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/src/RedLock.php b/src/RedLock.php index 5f6770a..4e9d267 100644 --- a/src/RedLock.php +++ b/src/RedLock.php @@ -2,8 +2,6 @@ class RedLock { - private $retryDelay; - private $retryCount; private $clockDriftFactor = 0.01; private $quorum; @@ -11,24 +9,19 @@ class RedLock private $servers = array(); private $instances = array(); - function __construct(array $servers, $retryDelay = 200, $retryCount = 3) + function __construct(array $servers) { $this->servers = $servers; - - $this->retryDelay = $retryDelay; - $this->retryCount = $retryCount; - $this->quorum = min(count($servers), (count($servers) / 2 + 1)); } - public function lock($resource, $ttl) + public function lock($resource, $ttl, $retryDelay = 200, $try_times = 3) { $this->initInstances(); $token = uniqid(); - $retry = $this->retryCount; - do { + while (true) { $n = 0; $startTime = microtime(true) * 1000; @@ -59,13 +52,15 @@ public function lock($resource, $ttl) } } - // Wait a random delay before to retry - $delay = mt_rand(floor($this->retryDelay / 2), $this->retryDelay); - usleep($delay * 1000); + $try_times--; - $retry--; + if ($try_times === 0) + break; - } while ($retry > 0); + // Wait a random delay before to retry + $delay = mt_rand(floor($retryDelay / 2), $retryDelay); + usleep($delay * 1000); + } return false; } From a08abfef5bdda8170eae896a7f96e757beff58b5 Mon Sep 17 00:00:00 2001 From: huangyg11 Date: Fri, 13 Mar 2015 19:19:33 +0800 Subject: [PATCH 2/2] Use the same one across all lifecycle. --- src/LockSinglon.php | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/LockSinglon.php diff --git a/src/LockSinglon.php b/src/LockSinglon.php new file mode 100644 index 0000000..d732eca --- /dev/null +++ b/src/LockSinglon.php @@ -0,0 +1,30 @@ +