From dc5becd0cb4a505c5686717c88d464d781dabcbf Mon Sep 17 00:00:00 2001 From: Robert Korulczyk Date: Sun, 23 Feb 2020 11:59:19 +0100 Subject: [PATCH 1/2] Increase frequency of lock tries when `$timeout` is used in `yii\redis\Mutex`. --- composer.json | 4 ++-- src/Mutex.php | 20 +++++++++++--------- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/composer.json b/composer.json index bcb59dacb..87827d014 100644 --- a/composer.json +++ b/composer.json @@ -18,11 +18,11 @@ } ], "require": { - "yiisoft/yii2": "~2.0.14" + "yiisoft/yii2": "~2.0.16" }, "require-dev": { "phpunit/phpunit": "<7", - "yiisoft/yii2-dev": "~2.0.14" + "yiisoft/yii2-dev": "~2.0.16" }, "autoload": { "psr-4": { "yii\\redis\\": "src" } diff --git a/src/Mutex.php b/src/Mutex.php index 2d0120c6d..d5da5b9e6 100644 --- a/src/Mutex.php +++ b/src/Mutex.php @@ -10,6 +10,7 @@ use Yii; use yii\base\InvalidConfigException; use yii\di\Instance; +use yii\mutex\RetryAcquireTrait; /** * Redis Mutex implements a mutex component using [redis](http://redis.io/) as the storage medium. @@ -58,6 +59,8 @@ */ class Mutex extends \yii\mutex\Mutex { + use RetryAcquireTrait; + /** * @var int the number of seconds in which the lock will be auto released. */ @@ -109,16 +112,15 @@ protected function acquireLock($name, $timeout = 0) { $key = $this->calculateKey($name); $value = Yii::$app->security->generateRandomString(20); - $waitTime = 0; - while (!$this->redis->executeCommand('SET', [$key, $value, 'NX', 'PX', (int) ($this->expire * 1000)])) { - $waitTime++; - if ($waitTime > $timeout) { - return false; - } - sleep(1); + + $result = $this->retryAcquire($timeout, function () use ($key, $value) { + return $this->redis->executeCommand('SET', [$key, $value, 'NX', 'PX', (int) ($this->expire * 1000)]); + }); + + if ($result) { + $this->_lockValues[$name] = $value; } - $this->_lockValues[$name] = $value; - return true; + return $result; } /** From 232cac66526891391da0a1dfd14e6c400de51b8d Mon Sep 17 00:00:00 2001 From: Robert Korulczyk Date: Sun, 23 Feb 2020 12:10:36 +0100 Subject: [PATCH 2/2] Changelog. [skip ci] --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e2e5295f3..e5a319741 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ Yii Framework 2 redis extension Change Log ------------------------ - Enh #195: Use `Instance::ensure()` to initialize `Session::$redis` (rob006) +- Enh #199: Increase frequency of lock tries when `$timeout` is used in `Mutex::acquire()` (rob006) 2.0.11 November 05, 2019