Final Class Yiisoft\Mutex\Redis\RedisMutex
| Inheritance | Yiisoft\Mutex\Redis\RedisMutex |
|---|---|
| Implements | Yiisoft\Mutex\MutexInterface |
| Uses Traits | Yiisoft\Mutex\RetryAcquireTrait |
RedisMutex implements mutex "lock" mechanism via Redis locks.
Public Methods
Method Details
| public mixed __construct ( string $name, \Predis\ClientInterface $client, integer $ttl = 30 ) | ||
| $name | string |
Mutex name. |
| $client | \Predis\ClientInterface |
Predis client instance to use. |
| $ttl | integer |
Number of seconds in which the lock will be auto released. |
public function __construct(string $name, ClientInterface $client, int $ttl = 30)
{
if ($ttl < 1) {
throw new InvalidArgumentException(
"TTL must be a positive number greater than zero, \"$ttl\" is received.",
);
}
$this->client = $client;
$this->lockKey = md5(self::class . $name);
$this->lockValue = Random::string(20);
$this->mutexName = $name;
$this->ttl = $ttl;
}
See also https://redis.io/topics/distlock.
| public acquire ( integer $timeout = 0 ) | ||
| $timeout | integer | |
public function acquire(int $timeout = 0): bool
{
return $this->retryAcquire($timeout, function (): bool {
if (
!$this->isExpired()
|| $this->client->set($this->lockKey, $this->lockValue, 'EX', $this->ttl, 'NX') === null
) {
return false;
}
$this->expired = $this->ttl + time();
return true;
});
}
See also https://redis.io/topics/distlock.
| public release ( ) |
public function release(): void
{
if ($this->isExpired()) {
return;
}
$released = (bool) $this->client->eval(
<<<LUA
if redis.call('GET',KEYS[1])==ARGV[1] then
return redis.call('DEL',KEYS[1])
else
return 0
end
LUA,
1,
$this->lockKey,
$this->lockValue,
);
if (!$released) {
throw new MutexReleaseException("Unable to release the \"$this->mutexName\" mutex.");
}
$this->expired = null;
}
Signup or Login in order to comment.