From 5d82c8d19e28df1553ff14696f6a315bec86c956 Mon Sep 17 00:00:00 2001 From: janua bisconti Date: Wed, 4 Dec 2024 14:32:35 +0100 Subject: [PATCH] riscritti in LUA i metodi lock e unlock --- src/SuperCacheManager.php | 39 ++++++++++++++++++++++++++------------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/src/SuperCacheManager.php b/src/SuperCacheManager.php index ee20a13..bb930d0 100644 --- a/src/SuperCacheManager.php +++ b/src/SuperCacheManager.php @@ -351,20 +351,25 @@ public function getOriginalKey(string $finalKey): string * @param string $key The lock key. * @return bool True if the lock was acquired, false otherwise. */ - public function lock(string $key, ?string $connection_name = null, ?int $ttl = 10): bool + public function lock(string $key, ?string $connection_name = null, int $ttl = 10, string $value = '1'): bool { - //return $this->redis->getRedisConnection($connection_name)->set($key, 1, 'EX', $ttl, 'NX'); $finalKey = $this->getFinalKey($key); - if ($this->has($finalKey)) { - return false; - } - $this->redis->getRedisConnection($connection_name)->set($finalKey, $this->serializeForRedis('1')); - - if ($ttl !== null) { - $this->redis->getRedisConnection($connection_name)->expire($finalKey, $ttl); - } - - return true; + $luaScript = <<<'LUA' + if redis.call("SET", KEYS[1], ARGV[2], "NX", "EX", tonumber(ARGV[1])) then + return 1 + else + return 0 + end + LUA; + + $result = $this->redis->getRedisConnection($connection_name)->eval( + $luaScript, + 1, // Number of keys + $finalKey, + $ttl, + $value + ); + return $result === 1; } /** @@ -375,6 +380,14 @@ public function lock(string $key, ?string $connection_name = null, ?int $ttl = 1 */ public function unLock(string $key, ?string $connection_name = null): void { - $this->redis->getRedisConnection($connection_name)->del($key); + $finalKey = $this->getFinalKey($key); + $luaScript = <<<'LUA' + redis.call('DEL', KEYS[1]); + LUA; + $this->redis->getRedisConnection($connection_name)->eval( + $luaScript, + 1, // Number of keys + $finalKey + ); } }