|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace RemiSan\Lock\Connection; |
|
4
|
|
|
|
|
5
|
|
|
use RemiSan\Lock\Connection; |
|
6
|
|
|
use RemiSan\Lock\Lock; |
|
7
|
|
|
|
|
8
|
|
|
class RedisConnection implements Connection |
|
9
|
|
|
{ |
|
10
|
|
|
/** @var float */ |
|
11
|
|
|
const CLOCK_DRIFT_FACTOR = 0.01; |
|
12
|
|
|
|
|
13
|
|
|
/** @var int */ |
|
14
|
|
|
const REDIS_EXPIRES_PRECISION = 2; |
|
15
|
|
|
|
|
16
|
|
|
/** @var \Redis */ |
|
17
|
|
|
private $redis; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* RedisConnection constructor. |
|
21
|
|
|
* |
|
22
|
|
|
* @param \Redis $redis |
|
23
|
|
|
*/ |
|
24
|
24 |
|
public function __construct(\Redis $redis) |
|
25
|
|
|
{ |
|
26
|
24 |
|
if (! $redis->isConnected()) { |
|
27
|
3 |
|
throw new \InvalidArgumentException('The Redis instance must be connected.'); |
|
28
|
|
|
} |
|
29
|
24 |
|
$this->redis = $redis; |
|
30
|
24 |
|
} |
|
31
|
|
|
/** |
|
32
|
|
|
* @inheritDoc |
|
33
|
|
|
*/ |
|
34
|
6 |
|
public function set(Lock $lock, $ttl = null) |
|
35
|
|
|
{ |
|
36
|
6 |
|
$options = ['NX']; |
|
37
|
|
|
|
|
38
|
6 |
|
if ($ttl) { |
|
|
|
|
|
|
39
|
3 |
|
$options['PX'] = (int) $ttl; |
|
40
|
2 |
|
} |
|
41
|
|
|
|
|
42
|
6 |
|
return (bool) $this->redis->set($lock->getResource(), (string) $lock->getToken(), $options); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* @inheritDoc |
|
47
|
|
|
*/ |
|
48
|
6 |
|
public function exists($resource) |
|
49
|
|
|
{ |
|
50
|
6 |
|
return (bool) $this->redis->get($resource); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* @inheritDoc |
|
55
|
|
|
*/ |
|
56
|
6 |
|
public function delete(Lock $lock) |
|
57
|
|
|
{ |
|
58
|
|
|
$script = ' |
|
59
|
|
|
if redis.call("GET", KEYS[1]) == ARGV[1] then |
|
60
|
|
|
return redis.call("DEL", KEYS[1]) |
|
61
|
|
|
else |
|
62
|
|
|
return 0 |
|
63
|
|
|
end |
|
64
|
6 |
|
'; |
|
65
|
|
|
|
|
66
|
6 |
|
return (bool) $this->redis->evaluate( |
|
67
|
4 |
|
$script, |
|
68
|
6 |
|
[$lock->getResource(), (string) $lock->getToken()], |
|
69
|
2 |
|
1 |
|
70
|
4 |
|
); |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
/** |
|
74
|
|
|
* @inheritDoc |
|
75
|
|
|
*/ |
|
76
|
3 |
|
public function getDrift($ttl) |
|
77
|
|
|
{ |
|
78
|
|
|
// Add 2 milliseconds to the drift to account for Redis expires |
|
79
|
|
|
// precision, which is 1 millisecond, plus 1 millisecond min drift |
|
80
|
|
|
// for small TTLs. |
|
81
|
|
|
|
|
82
|
3 |
|
$minDrift = ($ttl) ? (int) ceil($ttl * self::CLOCK_DRIFT_FACTOR) : 0; |
|
83
|
|
|
|
|
84
|
3 |
|
return $minDrift + self::REDIS_EXPIRES_PRECISION; |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|
In PHP, under loose comparison (like
==, or!=, orswitchconditions), values of different types might be equal.For
integervalues, zero is a special case, in particular the following results might be unexpected: