yf_wrapper_redlock classRelock algorithm http://antirez.com/news/77 Forked from https://github.com/ronnylt/redlock-php.
| File | plugins/redis/classes/yf_wrapper_redlock.class.php |
|---|---|
| Use | _class('wrapper_redlock') |
| Property | Default | Description |
|---|---|---|
| None declared in this class. | ||
public function lock($resource, $ttl)
public function lock($resource, $ttl)
{
$this->init_instances();
$token = uniqid();
$retry = $this->retry_count;
do {
$n = 0;
$start_time = microtime(true) * 1000;
foreach ((array) $this->instances as $instance) {
if ($this->lock_instance($instance, $resource, $token, $ttl)) {
$n++;
}
}
// Add 2 milliseconds to the drift to account for Redis expires
// precision, which is 1 millisecond, plus 1 millisecond min drift for small TTLs.
$drift = ($ttl * $this->clock_drift_factor) + 2;
$validity_time = $ttl - (microtime(true) * 1000 - $start_time) - $drift;
if ($n >= $this->quorum && $validity_time > 0) {
return [
'validity' => $validity_time,
'resource' => $resource,
'token' => $token,
];
}
foreach ((array) $this->instances as $instance) {
$this->unlock_instance($instance, $resource, $token);
}
// Wait a random delay before to retry
$delay = mt_rand(floor($this->retry_delay / 2), $this->retry_delay);
usleep($delay * 1000);
$retry--;
} while ($retry > 0);
return false;
}
public function setup(array $params = [])
$params array public function setup(array $params = [])
{
$this->servers = ($params['servers'] ?? null) ?: [[
$this->_get_conf('REDIS_HOST', '127.0.0.1', $params),
$this->_get_conf('REDIS_PORT', 6379, $params),
$timeout = 0.01,
]];
$this->quorum = min(count((array) $this->servers), (count((array) $this->servers) / 2 + 1));
if ($params['instances']) {
$this->instances = $params['instances'];
$this->quorum = min(count((array) $this->instances), (count((array) $this->instances) / 2 + 1));
}
$this->retry_delay = ($params['retry_delay'] ?? null) ?: 200;
$this->retry_count = ($params['retry_count'] ?? null) ?: 3;
}
public function unlock(array $lock)
$lock array public function unlock(array $lock)
{
$this->init_instances();
$resource = $lock['resource'];
$token = $lock['token'];
foreach ((array) $this->instances as $instance) {
$this->unlock_instance($instance, $resource, $token);
}
}
_ hooks and helpers; not routable as page actionspublic function _init()
public function _init()
{
$this->setup();
if ( ! $this->instances) {
$redis = redis();
$redis->connect();
$this->instances[] = $redis;
}
}