Skip to content

Commit c097bed

Browse files
committed
fix lock release on fatal error and SIGTERM
1 parent 8457cc4 commit c097bed

File tree

1 file changed

+23
-8
lines changed

1 file changed

+23
-8
lines changed

src/RedisSimpleLock.php

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ public function __construct($identifier, Client $client, $ttl = 10000, LoggerInt
3232
$this->ttl = $ttl;
3333
$this->logger = $logger ?: new NullLogger;
3434
$this->id = mt_rand();
35+
register_shutdown_function($this->releaseClosure());
3536
}
3637

3738
public function acquire()
@@ -48,18 +49,32 @@ public function acquire()
4849

4950
public function release()
5051
{
51-
$script = <<<LUA
52-
if redis.call("get", KEYS[1]) == ARGV[1] then
53-
return redis.call("del", KEYS[1])
54-
end
55-
LUA;
56-
if ($this->client->eval($script, 1, $this->identifier, $this->id)) {
57-
$this->logger->debug("lock released on {identifier}", ["identifier" => $this->identifier]);
58-
}
52+
$closure = $this->releaseClosure();
53+
$closure();
5954
}
6055

6156
public function __destruct()
6257
{
6358
$this->release();
6459
}
60+
61+
private function releaseClosure()
62+
{
63+
$client = $this->client;
64+
$id = $this->id;
65+
$identifier = $this->identifier;
66+
$logger = $this->logger;
67+
68+
$closure = function () use ($client, $identifier, $id, $logger) {
69+
$script = <<<LUA
70+
if redis.call("get", KEYS[1]) == ARGV[1] then
71+
return redis.call("del", KEYS[1])
72+
end
73+
LUA;
74+
if ($client->eval($script, 1, $identifier, $id)) {
75+
$logger->debug("lock released on {identifier}", ["identifier" => $identifier]);
76+
}
77+
};
78+
return $closure->bindTo(null);
79+
}
6580
}

0 commit comments

Comments
 (0)