/
Mutex.php
65 lines (55 loc) · 1.23 KB
/
Mutex.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
namespace Intersvyaz\CacheMutex;
use Yii;
use yii\caching\Cache;
class Mutex extends \yii\mutex\Mutex
{
/**
* @var string|Cache
*/
public $cache = 'cache';
/**
* @inheritdoc
*/
public function init()
{
parent::init();
$this->cache = is_string($this->cache) ? Yii::$app->get($this->cache, false) : $this->cache;
}
/**
* @inheritdoc
*/
protected function acquireLock($name, $timeout = 0)
{
if (!$this->cache instanceof Cache) {
return false;
}
$waitTime = 0;
while ($this->cache->get($this->getCacheKey($name)) !== false) {
$waitTime++;
if ($waitTime > $timeout) {
return false;
}
sleep(1);
}
return $this->cache->set($this->getCacheKey($name), true);
}
/**
* @inheritdoc
*/
protected function releaseLock($name)
{
if (!$this->cache instanceof Cache) {
return false;
}
return $this->cache->delete($this->getCacheKey($name));
}
/**
* @param string $name
* @return string
*/
private function getCacheKey($name)
{
return md5($name);
}
}