Skip to content

Commit

Permalink
riscritti in LUA i metodi lock e unlock
Browse files Browse the repository at this point in the history
  • Loading branch information
januabisconti committed Dec 4, 2024
1 parent 459fe7d commit 5d82c8d
Showing 1 changed file with 26 additions and 13 deletions.
39 changes: 26 additions & 13 deletions src/SuperCacheManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand All @@ -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
);
}
}

0 comments on commit 5d82c8d

Please sign in to comment.