1 | <?php |
||
41 | class RedisLockStrategy implements LockingStrategyInterface |
||
42 | { |
||
43 | /** |
||
44 | * @var \Redis A key-value data store |
||
45 | */ |
||
46 | private $redis; |
||
47 | |||
48 | /** |
||
49 | * @var string The locking subject, i.e. a string to discriminate the lock |
||
50 | */ |
||
51 | private $subject; |
||
52 | |||
53 | /** |
||
54 | * @var boolean TRUE if lock is acquired |
||
55 | */ |
||
56 | private $isAcquired = false; |
||
57 | |||
58 | /** |
||
59 | * @var int Seconds the lock remains persistent |
||
60 | */ |
||
61 | private $ttl = 3600; |
||
62 | |||
63 | /** |
||
64 | * @var int Seconds to wait for a lock |
||
65 | */ |
||
66 | private $blTo = 60; |
||
67 | |||
68 | /** |
||
69 | * @inheritdoc |
||
70 | */ |
||
71 | 10 | public function __construct($subject) |
|
123 | |||
124 | /** |
||
125 | * @inheritdoc |
||
126 | */ |
||
127 | 10 | public static function getCapabilities() |
|
131 | |||
132 | /** |
||
133 | * @inheritdoc |
||
134 | */ |
||
135 | 10 | public static function getPriority() |
|
139 | |||
140 | /** |
||
141 | * @inheritdoc |
||
142 | */ |
||
143 | 4 | public function acquire($mode = self::LOCK_CAPABILITY_EXCLUSIVE) |
|
144 | { |
||
145 | 4 | if ($this->isAcquired) { |
|
146 | return true; |
||
147 | } |
||
148 | |||
149 | 4 | if (!$this->redis->exists($this->subject)) { |
|
150 | 1 | throw new LockAcquireException('lock entry could not be found'); |
|
151 | } |
||
152 | |||
153 | 4 | if ($mode & self::LOCK_CAPABILITY_NOBLOCK) { |
|
154 | |||
155 | // this does not block |
||
156 | $this->isAcquired = (bool) $this->redis->lPop($this->subject); |
||
157 | |||
158 | if (!$this->isAcquired) { |
||
159 | throw new LockAcquireWouldBlockException('could not acquire lock'); |
||
160 | } |
||
161 | } else { |
||
162 | |||
163 | // this blocks iff the list is empty |
||
164 | 4 | $this->isAcquired = (bool) $this->redis->blPop([$this->subject], $this->blTo); |
|
165 | |||
166 | 4 | if (!$this->isAcquired) { |
|
167 | throw new LockAcquireException('could not acquire lock'); |
||
168 | } |
||
169 | } |
||
170 | |||
171 | 4 | return true; |
|
172 | } |
||
173 | |||
174 | /** |
||
175 | * @inheritdoc |
||
176 | */ |
||
177 | 1 | public function isAcquired() |
|
181 | |||
182 | /** |
||
183 | * @inheritdoc |
||
184 | */ |
||
185 | 2 | public function destroy() |
|
189 | |||
190 | /** |
||
191 | * @inheritdoc |
||
192 | */ |
||
193 | public function release() |
||
203 | |||
204 | } |
||
205 |