Skip to content

Commit 48affb6

Browse files
authored
Fix #199: Increase frequency of lock tries when $timeout is used in Mutex::acquire()
1 parent f02d3f5 commit 48affb6

File tree

3 files changed

+14
-11
lines changed

3 files changed

+14
-11
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ Yii Framework 2 redis extension Change Log
55
------------------------
66

77
- Enh #195: Use `Instance::ensure()` to initialize `Session::$redis` (rob006)
8+
- Enh #199: Increase frequency of lock tries when `$timeout` is used in `Mutex::acquire()` (rob006)
89

910

1011
2.0.11 November 05, 2019

composer.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,11 @@
1818
}
1919
],
2020
"require": {
21-
"yiisoft/yii2": "~2.0.14"
21+
"yiisoft/yii2": "~2.0.16"
2222
},
2323
"require-dev": {
2424
"phpunit/phpunit": "<7",
25-
"yiisoft/yii2-dev": "~2.0.14"
25+
"yiisoft/yii2-dev": "~2.0.16"
2626
},
2727
"autoload": {
2828
"psr-4": { "yii\\redis\\": "src" }

src/Mutex.php

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
use Yii;
1111
use yii\base\InvalidConfigException;
1212
use yii\di\Instance;
13+
use yii\mutex\RetryAcquireTrait;
1314

1415
/**
1516
* Redis Mutex implements a mutex component using [redis](http://redis.io/) as the storage medium.
@@ -58,6 +59,8 @@
5859
*/
5960
class Mutex extends \yii\mutex\Mutex
6061
{
62+
use RetryAcquireTrait;
63+
6164
/**
6265
* @var int the number of seconds in which the lock will be auto released.
6366
*/
@@ -109,16 +112,15 @@ protected function acquireLock($name, $timeout = 0)
109112
{
110113
$key = $this->calculateKey($name);
111114
$value = Yii::$app->security->generateRandomString(20);
112-
$waitTime = 0;
113-
while (!$this->redis->executeCommand('SET', [$key, $value, 'NX', 'PX', (int) ($this->expire * 1000)])) {
114-
$waitTime++;
115-
if ($waitTime > $timeout) {
116-
return false;
117-
}
118-
sleep(1);
115+
116+
$result = $this->retryAcquire($timeout, function () use ($key, $value) {
117+
return $this->redis->executeCommand('SET', [$key, $value, 'NX', 'PX', (int) ($this->expire * 1000)]);
118+
});
119+
120+
if ($result) {
121+
$this->_lockValues[$name] = $value;
119122
}
120-
$this->_lockValues[$name] = $value;
121-
return true;
123+
return $result;
122124
}
123125

124126
/**

0 commit comments

Comments
 (0)