/
Lock.php
84 lines (76 loc) · 1.83 KB
/
Lock.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
namespace PHPDaemon\Clients\Redis;
use PHPDaemon\Utils\Crypt;
/**
* @package NetworkClients
* @subpackage RedisClient
* @author Vasily Zorin <maintainer@daemon.io>
*/
class Lock
{
use \PHPDaemon\Traits\ClassWatchdog;
use \PHPDaemon\Traits\StaticObjectWatchdog;
protected $pool;
protected $timeout;
protected $token;
protected $key;
/**
* Constructor
* @param string $key
* @param integer $timeout
* @param Pool $pool
*/
public function __construct($key, $timeout, $pool)
{
$this->pool = $pool;
$this->timeout = $timeout;
$this->key = $key;
}
/**
* @TODO
* @param integer $timeout
* @return this
*/
public function timeout($timeout)
{
$this->timeout = $timeout;
return $this;
}
/**
* @TODO
* @param callable $cb
* @callback $cb ( )
* @return this
*/
public function acquire($cb)
{
Crypt::randomString(16, null, function ($token) use ($cb) {
$this->token = $token;
$this->pool->set($this->key, $this->token, 'NX', 'EX', $this->timeout, function ($redis) use ($cb) {
$cb($this, $redis->result === 'OK', $redis);
});
});
return $this;
}
/**
* @TODO
* @param callable $cb
* @callback $cb ( )
* @return this
*/
public function release($cb = null)
{
$this->pool->eval(
'if redis.call("get",KEYS[1]) == ARGV[1] then return redis.call("del",KEYS[1]) else return 0 end',
1,
$this->key,
$this->token,
function ($redis) use ($cb) {
if ($cb !== null) {
$cb($this, $redis->result, $redis);
}
}
);
return $this;
}
}