Class RedisLockEngine
Redis-based lock engine.
Uses Redis SET with NX and EX options for atomic lock acquisition. This provides a reliable distributed locking mechanism.
Supports both a single Redis node (or primary behind a proxy) and
Redis Cluster via phpredis' RedisCluster client. Cluster mode is
enabled by providing nodes (and optionally clusterName).
Configuration options:
host: Redis server hostname (default: '127.0.0.1'). Non-cluster only.port: Redis server port (default: 6379). Non-cluster only.password: Redis server password (default: false).database: Redis database index (default: 0). Non-cluster only.timeout: Connection timeout in seconds (default: 0).readTimeout: Read timeout in seconds (default: 0). Cluster only.persistent: Use persistent connections (default: true).prefix: Prefix for lock keys (default: 'lock_').ttl: Default lock TTL in seconds (default: 300).nodes: List of<ip>:<port>seed nodes for Redis Cluster. Presence of this option (orclusterName) switches the engine to cluster mode.clusterName: Named cluster entry configured viaredis.clusters.seeds.failover: Cluster failover mode (distribute,distribute_slaves,error,none). Cluster only.tls: When true, enables TLS for cluster connections. Cluster only.
Property Summary
-
$_config protected
array<string, mixed>Runtime config
-
$_configInitialized protected
boolWhether the config property has already been configured with defaults
-
$_defaultConfig protected
array<string, mixed>Default configuration.
-
$_redis protected
Redis|RedisClusterRedis connection.
Method Summary
-
_configDelete() protected
Deletes a single config key.
-
_configRead() protected
Reads a config key.
-
_configWrite() protected
Writes a config key.
-
_connect() protected
Connect to Redis server or cluster.
-
acquire() public
Acquire a lock for the given resource.
-
acquireBlocking() public
Acquire a lock, waiting up to $timeout seconds if necessary.
-
configShallow() public
Merge provided config with existing config. Unlike
config()which does a recursive merge for nested keys, this method does a simple merge. -
connectRedis() protected
Connect to a single Redis server.
-
connectRedisCluster() protected
Connect to a Redis Cluster.
-
deleteConfig() public
Deletes a config key.
-
ensureValidResource() protected
Ensure the resource identifier is valid.
-
forceRelease() public
Force release a lock without ownership verification.
-
generateToken() protected
Generate a unique token for lock ownership.
-
getConfig() public
Returns the config.
-
getConfigOrFail() public
Returns the config for this specific key.
-
init() public
Initialize the Redis lock engine.
-
isLocked() public
Check if a resource is currently locked.
-
key() protected
Generate the full key for a resource.
-
refresh() public
Refresh a lock's TTL.
-
release() public
Release a lock.
-
setConfig() public
Sets the config.
Method Detail
_configDelete() ¶ protected
_configDelete(string $key): void
Deletes a single config key.
Parameters
-
string$key Key to delete.
Returns
voidThrows
Cake\Core\Exception\CakeExceptionif attempting to clobber existing config
_configRead() ¶ protected
_configRead(string|null $key): $key is null ? array : mixed
Reads a config key.
Parameters
-
string|null$key Key to read.
Returns
$key is null ? array : mixed_configWrite() ¶ protected
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
Writes a config key.
Parameters
-
array<string, mixed>|string$key Key to write to.
-
mixed$value Value to write.
-
string|bool$merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
Returns
voidThrows
Cake\Core\Exception\CakeExceptionif attempting to clobber existing config
_connect() ¶ protected
_connect(): bool
Connect to Redis server or cluster.
Returns
boolTrue if connection was successful.
acquire() ¶ public
acquire(string $resource, int $ttl = 300): Cake\Lock\AcquiredLock|null
Acquire a lock for the given resource.
Uses Redis SET with NX (only set if not exists) and EX (expiry in seconds) for atomic lock acquisition.
Parameters
-
string$resource The resource identifier to lock.
-
int$ttl optional Time-to-live in seconds.
Returns
Cake\Lock\AcquiredLock|nullReturns an AcquiredLock on success, null on failure.
acquireBlocking() ¶ public
acquireBlocking(string $resource, int $ttl = 300, int $timeout = 10, int $retryInterval = 100): Cake\Lock\AcquiredLock|null
Acquire a lock, waiting up to $timeout seconds if necessary.
This is a default blocking implementation that repeatedly attempts to acquire the lock. Engines may override this with more efficient implementations.
Parameters
-
string$resource The resource identifier to lock.
-
int$ttl optional Time-to-live in seconds for the lock.
-
int$timeout optional Maximum time in seconds to wait for the lock.
-
int$retryInterval optional Milliseconds to wait between retry attempts.
Returns
Cake\Lock\AcquiredLock|nullReturns an AcquiredLock on success, null on timeout.
configShallow() ¶ public
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
Merge provided config with existing config. Unlike config() which does
a recursive merge for nested keys, this method does a simple merge.
Setting a specific value:
$this->configShallow('key', $value);
Setting a nested value:
$this->configShallow('some.nested.key', $value);
Updating multiple config settings at the same time:
$this->configShallow(['one' => 'value', 'another' => 'value']);
Parameters
-
array<string, mixed>|string$key The key to set, or a complete array of configs.
-
mixed|null$value optional The value to set.
Returns
$thisconnectRedis() ¶ protected
connectRedis(): bool
Connect to a single Redis server.
Returns
boolTrue if connection was successful.
connectRedisCluster() ¶ protected
connectRedisCluster(): bool
Connect to a Redis Cluster.
Returns
boolTrue if connection was successful.
deleteConfig() ¶ public
deleteConfig(string $key): $this
Deletes a config key.
Parameters
-
string$key Key to delete. It can be a dot separated string to delete nested keys.
Returns
$thisensureValidResource() ¶ protected
ensureValidResource(string $resource): void
Ensure the resource identifier is valid.
Parameters
-
string$resource The resource to validate.
Returns
voidThrows
Cake\Lock\Exception\InvalidArgumentExceptionIf resource is invalid.
forceRelease() ¶ public
forceRelease(string $resource): bool
Force release a lock without ownership verification.
WARNING: This should only be used for administrative purposes as it bypasses owner verification and may cause race conditions.
Parameters
-
string$resource The resource identifier to force release.
Returns
boolTrue if the lock was released, false otherwise.
generateToken() ¶ protected
generateToken(): string
Generate a unique token for lock ownership.
Returns
stringA unique token string.
getConfig() ¶ public
getConfig(string|null $key = null, mixed $default = null): $key is null ? array : mixed
Returns the config.
Usage
Reading the whole config:
$this->getConfig();
Reading a specific value:
$this->getConfig('key');
Reading a nested value:
$this->getConfig('some.nested.key');
Reading with default value:
$this->getConfig('some-key', 'default-value');
Parameters
-
string|null$key optional The key to get or null for the whole config.
-
mixed$default optional The return value when the key does not exist.
Returns
$key is null ? array : mixedConfiguration data at the named key or null if the key does not exist.
getConfigOrFail() ¶ public
getConfigOrFail(string $key): mixed
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
Parameters
-
string$key The key to get.
Returns
mixedConfiguration data at the named key
Throws
InvalidArgumentExceptioninit() ¶ public
init(array<string, mixed> $config = []): bool
Initialize the Redis lock engine.
Parameters
-
array<string, mixed>$config optional Configuration options.
Returns
boolTrue if initialization was successful.
Throws
Cake\Core\Exception\CakeExceptionIf redis extension is not loaded.
isLocked() ¶ public
isLocked(string $resource): bool
Check if a resource is currently locked.
Note: This is a point-in-time check and the lock status may change immediately after this method returns.
Parameters
-
string$resource The resource identifier to check.
Returns
boolTrue if the resource is locked, false otherwise.
key() ¶ protected
key(string $resource): string
Generate the full key for a resource.
Parameters
-
string$resource The resource identifier.
Returns
stringThe prefixed key.
Throws
Cake\Lock\Exception\InvalidArgumentExceptionIf resource is invalid.
refresh() ¶ public
refresh(Cake\Lock\AcquiredLock $lock, int|null $ttl = null): bool
Refresh a lock's TTL.
Uses a Lua script to atomically verify ownership and extend TTL.
Parameters
-
Cake\Lock\AcquiredLock$lock The lock instance to refresh.
-
int|null$ttl optional New TTL in seconds. If null, uses the original TTL.
Returns
boolTrue if the lock was refreshed, false otherwise.
release() ¶ public
release(Cake\Lock\AcquiredLock $lock): bool
Release a lock.
Uses a Lua script for atomic check-and-delete to ensure only the lock owner can release the lock.
Parameters
-
Cake\Lock\AcquiredLock$lock The lock instance to release.
Returns
boolTrue if the lock was released, false otherwise.
setConfig() ¶ public
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
Sets the config.
Usage
Setting a specific value:
$this->setConfig('key', $value);
Setting a nested value:
$this->setConfig('some.nested.key', $value);
Updating multiple config settings at the same time:
$this->setConfig(['one' => 'value', 'another' => 'value']);
Parameters
-
array<string, mixed>|string$key The key to set, or a complete array of configs.
-
mixed|null$value optional The value to set.
-
bool$merge optional Whether to recursively merge or overwrite existing config, defaults to true.
Returns
$thisThrows
Cake\Core\Exception\CakeExceptionWhen trying to set a key that is invalid.
Property Detail
$_configInitialized ¶ protected
Whether the config property has already been configured with defaults
Type
bool$_defaultConfig ¶ protected
Default configuration.
prefix: Prefix for all lock keys. Useful for namespacing.ttl: Default time-to-live in seconds for locks.
Type
array<string, mixed>