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) |
|
114 | |||
115 | /** |
||
116 | * @inheritdoc |
||
117 | */ |
||
118 | 10 | public static function getCapabilities() |
|
122 | |||
123 | /** |
||
124 | * @inheritdoc |
||
125 | */ |
||
126 | 10 | public static function getPriority() |
|
130 | |||
131 | /** |
||
132 | * @inheritdoc |
||
133 | */ |
||
134 | 3 | public function acquire($mode = self::LOCK_CAPABILITY_EXCLUSIVE) |
|
135 | { |
||
136 | 3 | if ($this->isAcquired) { |
|
137 | return true; |
||
138 | } |
||
139 | |||
140 | 3 | if ($mode & self::LOCK_CAPABILITY_EXCLUSIVE) { |
|
141 | |||
142 | 3 | if ($mode & self::LOCK_CAPABILITY_NOBLOCK) { |
|
143 | |||
144 | // this does not block |
||
145 | $this->isAcquired = (bool) $this->redis->lPop($this->subject); |
||
146 | |||
147 | if (!$this->isAcquired) { |
||
148 | throw new LockAcquireWouldBlockException('could not acquire lock'); |
||
149 | } |
||
150 | } else { |
||
151 | |||
152 | // this blocks iff the list is empty |
||
153 | 3 | $this->isAcquired = (bool) $this->redis->blPop([$this->subject], $this->blTo); |
|
154 | |||
155 | 3 | if (!$this->isAcquired) { |
|
156 | 3 | throw new LockAcquireException('could not acquire lock'); |
|
157 | } |
||
158 | } |
||
159 | |||
160 | } else { |
||
161 | throw new LockAcquireException('insufficient capabilities'); |
||
162 | } |
||
163 | |||
164 | 3 | return true; |
|
165 | } |
||
166 | |||
167 | /** |
||
168 | * @inheritdoc |
||
169 | */ |
||
170 | 1 | public function isAcquired() |
|
174 | |||
175 | /** |
||
176 | * @inheritdoc |
||
177 | */ |
||
178 | 2 | public function destroy() |
|
182 | |||
183 | /** |
||
184 | * @inheritdoc |
||
185 | */ |
||
186 | public function release() |
||
196 | |||
197 | /** |
||
198 | * create synchronization object, i.e. |
||
199 | * a simple list with some single random value |
||
200 | * |
||
201 | * @return boolean TRUE on success |
||
202 | * @throws LockCreateException |
||
203 | */ |
||
204 | 6 | private function create() |
|
216 | |||
217 | } |
||
218 |