0 follower

Final Class Yiisoft\Mutex\Redis\RedisMutex

InheritanceYiisoft\Mutex\Redis\RedisMutex
ImplementsYiisoft\Mutex\MutexInterface
Uses TraitsYiisoft\Mutex\RetryAcquireTrait

RedisMutex implements mutex "lock" mechanism via Redis locks.

Method Details

Hide inherited methods

__construct() public method

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;
}

            
__destruct() public method

public mixed __destruct ( )

                public function __destruct()
{
    $this->release();
}

            
acquire() public method
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;
    });
}

            
release() public method
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;
}