Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6092052a19 | ||
|
|
28dcdf6c1d | ||
|
|
9ccaf4ab11 | ||
|
|
d6cbd34e8f | ||
|
|
a7bb060bbd | ||
|
|
c20f00cc2a | ||
|
|
55cd4c5ddb | ||
|
|
1e3c0631d7 | ||
|
|
5d359453e6 | ||
|
|
72f50116d6 |
No files matched your search
+386
@@ -0,0 +1,386 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace dominion\cache;
|
||||||
|
|
||||||
|
use Yii;
|
||||||
|
use yii\base\Component;
|
||||||
|
use yii\helpers\Inflector;
|
||||||
|
use Redis;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Работа череез однк ноду
|
||||||
|
* пример конфига
|
||||||
|
*
|
||||||
|
* [
|
||||||
|
* 'class' => 'dominion\cache\Connection',
|
||||||
|
* 'parameters' => [
|
||||||
|
* 'host' => 'node1.redis.service.optiweb',
|
||||||
|
* 'port' => '6379',
|
||||||
|
* 'prefix' => "prefix",
|
||||||
|
* 'username' => '',
|
||||||
|
* 'password' => 'password',
|
||||||
|
* 'database' => 0,
|
||||||
|
* 'read_timeout' => 0,
|
||||||
|
* 'scan' => ,
|
||||||
|
* 'name' => ,
|
||||||
|
* 'serializer' => ,
|
||||||
|
* 'compression' =>,
|
||||||
|
* 'compression_level' =>
|
||||||
|
* ]
|
||||||
|
* ]
|
||||||
|
*/
|
||||||
|
class Connection extends Component
|
||||||
|
{
|
||||||
|
public $parameters = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var array List of available redis commands.
|
||||||
|
* @see https://redis.io/commands
|
||||||
|
*/
|
||||||
|
public $redisCommands = [
|
||||||
|
'APPEND', // Append a value to a key
|
||||||
|
'AUTH', // Authenticate to the server
|
||||||
|
'BGREWRITEAOF', // Asynchronously rewrite the append-only file
|
||||||
|
'BGSAVE', // Asynchronously save the dataset to disk
|
||||||
|
'BITCOUNT', // Count set bits in a string
|
||||||
|
'BITFIELD', // Perform arbitrary bitfield integer operations on strings
|
||||||
|
'BITOP', // Perform bitwise operations between strings
|
||||||
|
'BITPOS', // Find first bit set or clear in a string
|
||||||
|
'BLPOP', // Remove and get the first element in a list, or block until one is available
|
||||||
|
'BRPOP', // Remove and get the last element in a list, or block until one is available
|
||||||
|
'BRPOPLPUSH', // Pop a value from a list, push it to another list and return it; or block until one is available
|
||||||
|
'CLIENT KILL', // Kill the connection of a client
|
||||||
|
'CLIENT LIST', // Get the list of client connections
|
||||||
|
'CLIENT GETNAME', // Get the current connection name
|
||||||
|
'CLIENT PAUSE', // Stop processing commands from clients for some time
|
||||||
|
'CLIENT REPLY', // Instruct the server whether to reply to commands
|
||||||
|
'CLIENT SETNAME', // Set the current connection name
|
||||||
|
'CLUSTER ADDSLOTS', // Assign new hash slots to receiving node
|
||||||
|
'CLUSTER COUNTKEYSINSLOT', // Return the number of local keys in the specified hash slot
|
||||||
|
'CLUSTER DELSLOTS', // Set hash slots as unbound in receiving node
|
||||||
|
'CLUSTER FAILOVER', // Forces a slave to perform a manual failover of its master.
|
||||||
|
'CLUSTER FORGET', // Remove a node from the nodes table
|
||||||
|
'CLUSTER GETKEYSINSLOT', // Return local key names in the specified hash slot
|
||||||
|
'CLUSTER INFO', // Provides info about Redis Cluster node state
|
||||||
|
'CLUSTER KEYSLOT', // Returns the hash slot of the specified key
|
||||||
|
'CLUSTER MEET', // Force a node cluster to handshake with another node
|
||||||
|
'CLUSTER NODES', // Get Cluster config for the node
|
||||||
|
'CLUSTER REPLICATE', // Reconfigure a node as a slave of the specified master node
|
||||||
|
'CLUSTER RESET', // Reset a Redis Cluster node
|
||||||
|
'CLUSTER SAVECONFIG', // Forces the node to save cluster state on disk
|
||||||
|
'CLUSTER SETSLOT', // Bind a hash slot to a specific node
|
||||||
|
'CLUSTER SLAVES', // List slave nodes of the specified master node
|
||||||
|
'CLUSTER SLOTS', // Get array of Cluster slot to node mappings
|
||||||
|
'COMMAND', // Get array of Redis command details
|
||||||
|
'COMMAND COUNT', // Get total number of Redis commands
|
||||||
|
'COMMAND GETKEYS', // Extract keys given a full Redis command
|
||||||
|
'COMMAND INFO', // Get array of specific Redis command details
|
||||||
|
'CONFIG GET', // Get the value of a configuration parameter
|
||||||
|
'CONFIG REWRITE', // Rewrite the configuration file with the in memory configuration
|
||||||
|
'CONFIG SET', // Set a configuration parameter to the given value
|
||||||
|
'CONFIG RESETSTAT', // Reset the stats returned by INFO
|
||||||
|
'DBSIZE', // Return the number of keys in the selected database
|
||||||
|
'DEBUG OBJECT', // Get debugging information about a key
|
||||||
|
'DEBUG SEGFAULT', // Make the server crash
|
||||||
|
'DECR', // Decrement the integer value of a key by one
|
||||||
|
'DECRBY', // Decrement the integer value of a key by the given number
|
||||||
|
'DEL', // Delete a key
|
||||||
|
'DISCARD', // Discard all commands issued after MULTI
|
||||||
|
'DUMP', // Return a serialized version of the value stored at the specified key.
|
||||||
|
'ECHO', // Echo the given string
|
||||||
|
'EVAL', // Execute a Lua script server side
|
||||||
|
'EVALSHA', // Execute a Lua script server side
|
||||||
|
'EXEC', // Execute all commands issued after MULTI
|
||||||
|
'EXISTS', // Determine if a key exists
|
||||||
|
'EXPIRE', // Set a key's time to live in seconds
|
||||||
|
'EXPIREAT', // Set the expiration for a key as a UNIX timestamp
|
||||||
|
'FLUSHALL', // Remove all keys from all databases
|
||||||
|
'FLUSHDB', // Remove all keys from the current database
|
||||||
|
'GEOADD', // Add one or more geospatial items in the geospatial index represented using a sorted set
|
||||||
|
'GEOHASH', // Returns members of a geospatial index as standard geohash strings
|
||||||
|
'GEOPOS', // Returns longitude and latitude of members of a geospatial index
|
||||||
|
'GEODIST', // Returns the distance between two members of a geospatial index
|
||||||
|
'GEORADIUS', // Query a sorted set representing a geospatial index to fetch members matching a given maximum distance from a point
|
||||||
|
'GEORADIUSBYMEMBER', // Query a sorted set representing a geospatial index to fetch members matching a given maximum distance from a member
|
||||||
|
'GET', // Get the value of a key
|
||||||
|
'GETBIT', // Returns the bit value at offset in the string value stored at key
|
||||||
|
'GETRANGE', // Get a substring of the string stored at a key
|
||||||
|
'GETSET', // Set the string value of a key and return its old value
|
||||||
|
'HDEL', // Delete one or more hash fields
|
||||||
|
'HEXISTS', // Determine if a hash field exists
|
||||||
|
'HGET', // Get the value of a hash field
|
||||||
|
'HGETALL', // Get all the fields and values in a hash
|
||||||
|
'HINCRBY', // Increment the integer value of a hash field by the given number
|
||||||
|
'HINCRBYFLOAT', // Increment the float value of a hash field by the given amount
|
||||||
|
'HKEYS', // Get all the fields in a hash
|
||||||
|
'HLEN', // Get the number of fields in a hash
|
||||||
|
'HMGET', // Get the values of all the given hash fields
|
||||||
|
'HMSET', // Set multiple hash fields to multiple values
|
||||||
|
'HSET', // Set the string value of a hash field
|
||||||
|
'HSETNX', // Set the value of a hash field, only if the field does not exist
|
||||||
|
'HSTRLEN', // Get the length of the value of a hash field
|
||||||
|
'HVALS', // Get all the values in a hash
|
||||||
|
'INCR', // Increment the integer value of a key by one
|
||||||
|
'INCRBY', // Increment the integer value of a key by the given amount
|
||||||
|
'INCRBYFLOAT', // Increment the float value of a key by the given amount
|
||||||
|
'INFO', // Get information and statistics about the server
|
||||||
|
'KEYS', // Find all keys matching the given pattern
|
||||||
|
'LASTSAVE', // Get the UNIX time stamp of the last successful save to disk
|
||||||
|
'LINDEX', // Get an element from a list by its index
|
||||||
|
'LINSERT', // Insert an element before or after another element in a list
|
||||||
|
'LLEN', // Get the length of a list
|
||||||
|
'LPOP', // Remove and get the first element in a list
|
||||||
|
'LPUSH', // Prepend one or multiple values to a list
|
||||||
|
'LPUSHX', // Prepend a value to a list, only if the list exists
|
||||||
|
'LRANGE', // Get a range of elements from a list
|
||||||
|
'LREM', // Remove elements from a list
|
||||||
|
'LSET', // Set the value of an element in a list by its index
|
||||||
|
'LTRIM', // Trim a list to the specified range
|
||||||
|
'MGET', // Get the values of all the given keys
|
||||||
|
'MIGRATE', // Atomically transfer a key from a Redis instance to another one.
|
||||||
|
'MONITOR', // Listen for all requests received by the server in real time
|
||||||
|
'MOVE', // Move a key to another database
|
||||||
|
'MSET', // Set multiple keys to multiple values
|
||||||
|
'MSETNX', // Set multiple keys to multiple values, only if none of the keys exist
|
||||||
|
'MULTI', // Mark the start of a transaction block
|
||||||
|
'OBJECT', // Inspect the internals of Redis objects
|
||||||
|
'PERSIST', // Remove the expiration from a key
|
||||||
|
'PEXPIRE', // Set a key's time to live in milliseconds
|
||||||
|
'PEXPIREAT', // Set the expiration for a key as a UNIX timestamp specified in milliseconds
|
||||||
|
'PFADD', // Adds the specified elements to the specified HyperLogLog.
|
||||||
|
'PFCOUNT', // Return the approximated cardinality of the set(s) observed by the HyperLogLog at key(s).
|
||||||
|
'PFMERGE', // Merge N different HyperLogLogs into a single one.
|
||||||
|
'PING', // Ping the server
|
||||||
|
'PSETEX', // Set the value and expiration in milliseconds of a key
|
||||||
|
'PSUBSCRIBE', // Listen for messages published to channels matching the given patterns
|
||||||
|
'PUBSUB', // Inspect the state of the Pub/Sub subsystem
|
||||||
|
'PTTL', // Get the time to live for a key in milliseconds
|
||||||
|
'PUBLISH', // Post a message to a channel
|
||||||
|
'PUNSUBSCRIBE', // Stop listening for messages posted to channels matching the given patterns
|
||||||
|
'QUIT', // Close the connection
|
||||||
|
'RANDOMKEY', // Return a random key from the keyspace
|
||||||
|
'READONLY', // Enables read queries for a connection to a cluster slave node
|
||||||
|
'READWRITE', // Disables read queries for a connection to a cluster slave node
|
||||||
|
'RENAME', // Rename a key
|
||||||
|
'RENAMENX', // Rename a key, only if the new key does not exist
|
||||||
|
'RESTORE', // Create a key using the provided serialized value, previously obtained using DUMP.
|
||||||
|
'ROLE', // Return the role of the instance in the context of replication
|
||||||
|
'RPOP', // Remove and get the last element in a list
|
||||||
|
'RPOPLPUSH', // Remove the last element in a list, prepend it to another list and return it
|
||||||
|
'RPUSH', // Append one or multiple values to a list
|
||||||
|
'RPUSHX', // Append a value to a list, only if the list exists
|
||||||
|
'SADD', // Add one or more members to a set
|
||||||
|
'SAVE', // Synchronously save the dataset to disk
|
||||||
|
'SCARD', // Get the number of members in a set
|
||||||
|
'SCRIPT DEBUG', // Set the debug mode for executed scripts.
|
||||||
|
'SCRIPT EXISTS', // Check existence of scripts in the script cache.
|
||||||
|
'SCRIPT FLUSH', // Remove all the scripts from the script cache.
|
||||||
|
'SCRIPT KILL', // Kill the script currently in execution.
|
||||||
|
'SCRIPT LOAD', // Load the specified Lua script into the script cache.
|
||||||
|
'SDIFF', // Subtract multiple sets
|
||||||
|
'SDIFFSTORE', // Subtract multiple sets and store the resulting set in a key
|
||||||
|
'SELECT', // Change the selected database for the current connection
|
||||||
|
'SET', // Set the string value of a key
|
||||||
|
'SETBIT', // Sets or clears the bit at offset in the string value stored at key
|
||||||
|
'SETEX', // Set the value and expiration of a key
|
||||||
|
'SETNX', // Set the value of a key, only if the key does not exist
|
||||||
|
'SETRANGE', // Overwrite part of a string at key starting at the specified offset
|
||||||
|
'SHUTDOWN', // Synchronously save the dataset to disk and then shut down the server
|
||||||
|
'SINTER', // Intersect multiple sets
|
||||||
|
'SINTERSTORE', // Intersect multiple sets and store the resulting set in a key
|
||||||
|
'SISMEMBER', // Determine if a given value is a member of a set
|
||||||
|
'SLAVEOF', // Make the server a slave of another instance, or promote it as master
|
||||||
|
'SLOWLOG', // Manages the Redis slow queries log
|
||||||
|
'SMEMBERS', // Get all the members in a set
|
||||||
|
'SMOVE', // Move a member from one set to another
|
||||||
|
'SORT', // Sort the elements in a list, set or sorted set
|
||||||
|
'SPOP', // Remove and return one or multiple random members from a set
|
||||||
|
'SRANDMEMBER', // Get one or multiple random members from a set
|
||||||
|
'SREM', // Remove one or more members from a set
|
||||||
|
'STRLEN', // Get the length of the value stored in a key
|
||||||
|
'SUBSCRIBE', // Listen for messages published to the given channels
|
||||||
|
'SUNION', // Add multiple sets
|
||||||
|
'SUNIONSTORE', // Add multiple sets and store the resulting set in a key
|
||||||
|
'SWAPDB', // Swaps two Redis databases
|
||||||
|
'SYNC', // Internal command used for replication
|
||||||
|
'TIME', // Return the current server time
|
||||||
|
'TOUCH', // Alters the last access time of a key(s). Returns the number of existing keys specified.
|
||||||
|
'TTL', // Get the time to live for a key
|
||||||
|
'TYPE', // Determine the type stored at key
|
||||||
|
'UNSUBSCRIBE', // Stop listening for messages posted to the given channels
|
||||||
|
'UNLINK', // Delete a key asynchronously in another thread. Otherwise it is just as DEL, but non blocking.
|
||||||
|
'UNWATCH', // Forget about all watched keys
|
||||||
|
'WAIT', // Wait for the synchronous replication of all the write commands sent in the context of the current connection
|
||||||
|
'WATCH', // Watch the given keys to determine execution of the MULTI/EXEC block
|
||||||
|
'XACK', // Removes one or multiple messages from the pending entries list (PEL) of a stream consumer group
|
||||||
|
'XADD', // Appends the specified stream entry to the stream at the specified key
|
||||||
|
'XCLAIM', // Changes the ownership of a pending message, so that the new owner is the consumer specified as the command argument
|
||||||
|
'XDEL', // Removes the specified entries from a stream, and returns the number of entries deleted
|
||||||
|
'XGROUP', // Manages the consumer groups associated with a stream data structure
|
||||||
|
'XINFO', // Retrieves different information about the streams and associated consumer groups
|
||||||
|
'XLEN', // Returns the number of entries inside a stream
|
||||||
|
'XPENDING', // Fetching data from a stream via a consumer group, and not acknowledging such data, has the effect of creating pending entries
|
||||||
|
'XRANGE', // Returns the stream entries matching a given range of IDs
|
||||||
|
'XREAD', // Read data from one or multiple streams, only returning entries with an ID greater than the last received ID reported by the caller
|
||||||
|
'XREADGROUP', // Special version of the XREAD command with support for consumer groups
|
||||||
|
'XREVRANGE', // Exactly like XRANGE, but with the notable difference of returning the entries in reverse order, and also taking the start-end range in reverse order
|
||||||
|
'XTRIM', // Trims the stream to a given number of items, evicting older items (items with lower IDs) if needed
|
||||||
|
'ZADD', // Add one or more members to a sorted set, or update its score if it already exists
|
||||||
|
'ZCARD', // Get the number of members in a sorted set
|
||||||
|
'ZCOUNT', // Count the members in a sorted set with scores within the given values
|
||||||
|
'ZINCRBY', // Increment the score of a member in a sorted set
|
||||||
|
'ZINTERSTORE', // Intersect multiple sorted sets and store the resulting sorted set in a new key
|
||||||
|
'ZLEXCOUNT', // Count the number of members in a sorted set between a given lexicographical range
|
||||||
|
'ZRANGE', // Return a range of members in a sorted set, by index
|
||||||
|
'ZRANGEBYLEX', // Return a range of members in a sorted set, by lexicographical range
|
||||||
|
'ZREVRANGEBYLEX', // Return a range of members in a sorted set, by lexicographical range, ordered from higher to lower strings.
|
||||||
|
'ZRANGEBYSCORE', // Return a range of members in a sorted set, by score
|
||||||
|
'ZRANK', // Determine the index of a member in a sorted set
|
||||||
|
'ZREM', // Remove one or more members from a sorted set
|
||||||
|
'ZREMRANGEBYLEX', // Remove all members in a sorted set between the given lexicographical range
|
||||||
|
'ZREMRANGEBYRANK', // Remove all members in a sorted set within the given indexes
|
||||||
|
'ZREMRANGEBYSCORE', // Remove all members in a sorted set within the given scores
|
||||||
|
'ZREVRANGE', // Return a range of members in a sorted set, by index, with scores ordered from high to low
|
||||||
|
'ZREVRANGEBYSCORE', // Return a range of members in a sorted set, by score, with scores ordered from high to low
|
||||||
|
'ZREVRANK', // Determine the index of a member in a sorted set, with scores ordered from high to low
|
||||||
|
'ZSCORE', // Get the score associated with the given member in a sorted set
|
||||||
|
'ZUNIONSTORE', // Add multiple sorted sets and store the resulting sorted set in a new key
|
||||||
|
'SCAN', // Incrementally iterate the keys space
|
||||||
|
'SSCAN', // Incrementally iterate Set elements
|
||||||
|
'HSCAN', // Incrementally iterate hash fields and associated values
|
||||||
|
'ZSCAN', // Incrementally iterate sorted sets elements and associated scores
|
||||||
|
];
|
||||||
|
|
||||||
|
public $redis = false;
|
||||||
|
|
||||||
|
public function __sleep()
|
||||||
|
{
|
||||||
|
$this->close();
|
||||||
|
return array_keys(get_object_vars($this));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getIsActive()
|
||||||
|
{
|
||||||
|
return $this->redis !== false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function open()
|
||||||
|
{
|
||||||
|
if (!$this->isActive)
|
||||||
|
{
|
||||||
|
Yii::debug('Opening redis DB connection: ' . var_export($this->parameters, true), __METHOD__);
|
||||||
|
$this->redis = $this->createClient($this->parameters);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function close()
|
||||||
|
{
|
||||||
|
if ($this->isActive)
|
||||||
|
{
|
||||||
|
Yii::debug('Closing DB connection: ' . var_export($this->parameters, true), __METHOD__);
|
||||||
|
$this->redis->disconnect();
|
||||||
|
$this->redis = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __call($name, $params)
|
||||||
|
{
|
||||||
|
$redisCommand = strtoupper(Inflector::camel2words($name, false));
|
||||||
|
if (in_array($redisCommand, $this->redisCommands))
|
||||||
|
{
|
||||||
|
return $this->executeCommand($redisCommand, $params);
|
||||||
|
}
|
||||||
|
|
||||||
|
return parent::__call($name, $params);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function executeCommand($name, $params = [])
|
||||||
|
{
|
||||||
|
$this->open();
|
||||||
|
Yii::debug("Executing Redis Command: {$name} " . var_export($params, true), __METHOD__);
|
||||||
|
return $this->redis->{$name}(...$params);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function createClient(array $config): Redis
|
||||||
|
{
|
||||||
|
$client = new Redis;
|
||||||
|
$this->establishConnection($client, $config);
|
||||||
|
if (!empty($config['password']))
|
||||||
|
{
|
||||||
|
if (isset($config['username']) && $config['username'] !== '' && is_string($config['password']))
|
||||||
|
{
|
||||||
|
$client->auth([$config['username'], $config['password']]);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
$client->auth($config['password']);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($config['database']))
|
||||||
|
{
|
||||||
|
$client->select((int) $config['database']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!empty($config['prefix']))
|
||||||
|
{
|
||||||
|
$client->setOption(Redis::OPT_PREFIX, $config['prefix']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!empty($config['read_timeout']))
|
||||||
|
{
|
||||||
|
$client->setOption(Redis::OPT_READ_TIMEOUT, $config['read_timeout']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!empty($config['scan']))
|
||||||
|
{
|
||||||
|
$client->setOption(Redis::OPT_SCAN, $config['scan']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!empty($config['name']))
|
||||||
|
{
|
||||||
|
$client->client('SETNAME', $config['name']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (array_key_exists('serializer', $config))
|
||||||
|
{
|
||||||
|
$client->setOption(Redis::OPT_SERIALIZER, $config['serializer']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (array_key_exists('compression', $config))
|
||||||
|
{
|
||||||
|
$client->setOption(Redis::OPT_COMPRESSION, $config['compression']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (array_key_exists('compression_level', $config))
|
||||||
|
{
|
||||||
|
$client->setOption(Redis::OPT_COMPRESSION_LEVEL, $config['compression_level']);
|
||||||
|
}
|
||||||
|
return $client;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function establishConnection($client, array $config)
|
||||||
|
{
|
||||||
|
$persistent = $config['persistent'] ?? false;
|
||||||
|
|
||||||
|
$parameters = [
|
||||||
|
$config['host'],
|
||||||
|
$config['port'],
|
||||||
|
isset($config['timeout']) ? $config['timeout'] : 0.0,
|
||||||
|
$persistent ? (isset($config['persistent_id']) ? $config['persistent_id'] : null) : null,
|
||||||
|
isset($config['retry_interval']) ? $config['retry_interval'] : 0,
|
||||||
|
];
|
||||||
|
|
||||||
|
if (version_compare(phpversion('redis'), '3.1.3', '>='))
|
||||||
|
{
|
||||||
|
$parameters[] = isset($config['read_timeout']) ? $config['read_timeout'] : 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (version_compare(phpversion('redis'), '5.3.0', '>=') && !is_null($context = isset($config['context']) ? $config['context'] : null))
|
||||||
|
{
|
||||||
|
$parameters[] = $context;
|
||||||
|
}
|
||||||
|
|
||||||
|
$client->{$persistent ? 'pconnect' : 'connect'}(...$parameters);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
# dominion/cache
|
||||||
|
|
||||||
|
Yii2-расширение для работы с Redis через PECL-расширение `redis`: низкоуровневое
|
||||||
|
подключение (одна нода или кластер под Redis Sentinel), статический facade для
|
||||||
|
кеширования моделей и `Session`, хранящий сессии в Redis.
|
||||||
|
|
||||||
|
Пакет используется в монорепо Kuvalda: `Connection`/`SentinelConnection` — как
|
||||||
|
компонент `redis` в `catalog-app`, `user-app`, `moderator-app` (переключение по
|
||||||
|
`REDIS_MODE`); `RedisCache` — базовый класс для
|
||||||
|
`catalog-app/helpers/CacheHelper.php`; `Session` — компонент `session` в
|
||||||
|
`user-app` и `moderator-app`.
|
||||||
|
|
||||||
|
## Требования
|
||||||
|
|
||||||
|
- PHP с PECL-расширением [`redis`](https://pecl.php.net/package/redis)
|
||||||
|
(`Redis`, `RedisSentinel`) — в `composer.json` зависимость не объявлена;
|
||||||
|
- `yiisoft/yii2 ~2.0` (см. `composer.json`);
|
||||||
|
- Redis-сервер ≥ 2.6.12 (для `Session`).
|
||||||
|
|
||||||
|
## Состав
|
||||||
|
|
||||||
|
| класс | зачем |
|
||||||
|
|---|---|
|
||||||
|
| `Connection` | ленивое подключение к одной ноде Redis, маппинг методов-камелКейс в redis-команды |
|
||||||
|
| `SentinelConnection` | наследник `Connection`: поиск master/slave через Redis Sentinel, чтения — на рабов |
|
||||||
|
| `RedisCache` | статический API поверх `Yii::$app->redis`: кеш моделей и массивов моделей, хеши, инвалидация, отложенное удаление |
|
||||||
|
| `Session` | `yii\web\Session` с хранением в Redis (порт `yii\redis\Session` под local-`Connection`) |
|
||||||
|
|
||||||
|
## Установка
|
||||||
|
|
||||||
|
Пакет лежит в приватном Gitea (`https://gitea.optiweb.ru/public/kuvalda-cache`),
|
||||||
|
ставится как зависимость composer-ом приложения:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
composer require dominion/cache
|
||||||
|
```
|
||||||
|
|
||||||
|
В dev-стенде монорепо `vendor/dominion` подменяется симлинком на локальный
|
||||||
|
checkout скриптом `composer-dev.sh` корневого репозитория.
|
||||||
|
|
||||||
|
## Конфигурация
|
||||||
|
|
||||||
|
### Одна нода (`Connection`)
|
||||||
|
|
||||||
|
```php
|
||||||
|
// config/db.php (или components в web.php)
|
||||||
|
'redis' => [
|
||||||
|
'class' => 'dominion\cache\Connection',
|
||||||
|
'parameters' => [
|
||||||
|
'host' => 'node1.redis.service.optiweb',
|
||||||
|
'port' => '6379',
|
||||||
|
'prefix' => 'catalog:', // Redis::OPT_PREFIX
|
||||||
|
'username' => '',
|
||||||
|
'password' => 'password',
|
||||||
|
'database' => 0,
|
||||||
|
'timeout' => 0.0,
|
||||||
|
'read_timeout' => 0,
|
||||||
|
'retry_interval' => 0,
|
||||||
|
'persistent' => false, // pconnect вместо connect
|
||||||
|
'persistent_id' => null,
|
||||||
|
'scan' => null, // Redis::OPT_SCAN
|
||||||
|
'name' => null, // CLIENT SETNAME
|
||||||
|
'serializer' => null, // Redis::OPT_SERIALIZER
|
||||||
|
'compression' => null, // Redis::OPT_COMPRESSION
|
||||||
|
'compression_level' => null, // Redis::OPT_COMPRESSION_LEVEL
|
||||||
|
'context' => null, // ext-redis >= 5.3.0
|
||||||
|
],
|
||||||
|
],
|
||||||
|
```
|
||||||
|
|
||||||
|
Подключение открывается лениво при первой команде (`open()`), `__sleep()`
|
||||||
|
закрывает сокет перед сериализацией компонента.
|
||||||
|
|
||||||
|
### Кластер через Sentinel (`SentinelConnection`)
|
||||||
|
|
||||||
|
Тот же `parameters`, вместо `host`/`port` — секция `sentinel_*`
|
||||||
|
(пример — `catalog-app/config/db.php`):
|
||||||
|
|
||||||
|
```php
|
||||||
|
'redis' => [
|
||||||
|
'class' => 'dominion\cache\SentinelConnection',
|
||||||
|
'parameters' => [
|
||||||
|
'sentinel_host' => ['sentinel1', 'sentinel2'], // массив или строка, перебор до живого
|
||||||
|
'sentinel_port' => 26379,
|
||||||
|
'sentinel_service' => 'mymaster',
|
||||||
|
'sentinel_timeout' => 0.2,
|
||||||
|
'sentinel_persistent' => null,
|
||||||
|
'sentinel_retry_interval' => 0,
|
||||||
|
'sentinel_read_timeout' => 0,
|
||||||
|
'sentinel_username' => '',
|
||||||
|
'sentinel_password' => '',
|
||||||
|
// общие для master и slave нод:
|
||||||
|
'password' => env('REDIS_CLUSTER_PASSWORD'),
|
||||||
|
'database' => env('REDIS_CLUSTER_DATABASE'),
|
||||||
|
'prefix' => env('REDIS_CLUSTER_PREFIX'),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
```
|
||||||
|
|
||||||
|
`createClient()` спрашивает у Sentinel topology и подключается к master'у; для
|
||||||
|
каждой валидной slave-ноды сразу создаётся отдельное соединение в `$slaves`.
|
||||||
|
`executeCommand()` отправляет на случайного раба только команды из белого
|
||||||
|
списка `$redisSlaveCommands` — по умолчанию `GET` и `HGET`, остальное идёт на
|
||||||
|
master.
|
||||||
|
|
||||||
|
### Сессии (`Session`)
|
||||||
|
|
||||||
|
```php
|
||||||
|
'session' => [
|
||||||
|
'class' => 'dominion\cache\Session',
|
||||||
|
'keyPrefix' => 'PHPREDIS_SESSION:', // по умолчанию substr(md5(Yii::$app->id), 0, 5)
|
||||||
|
// 'redis' => 'redis', // id компонента-подключения
|
||||||
|
],
|
||||||
|
```
|
||||||
|
|
||||||
|
Ключ в Redis — `keyPrefix + md5([class, sessionId])`, запись идёт с `EX` =
|
||||||
|
`session.timeout`, поддерживается strict mode (`useStrictMode`) с форс-регенерацией
|
||||||
|
несуществующего id.
|
||||||
|
|
||||||
|
## Использование
|
||||||
|
|
||||||
|
### Connection как компонент приложения
|
||||||
|
|
||||||
|
Методы резолвятся через `__call`: имя метода приводится к верхнему регистру
|
||||||
|
через `Inflector::camel2words(..., false)` и сверяется с белым списком
|
||||||
|
`$redisCommands`, затем вызывается на PECL-клиенте. Команды нужно писать
|
||||||
|
строчным слитным именем (`hget`, `hset`, `hgetall`, `zadd`), иначе
|
||||||
|
`hGetAll` превратится в `H GET ALL`, не найдётся в списке и уйдёт в
|
||||||
|
`UnknownMethodException`. Команды из двух слов и прямые вызовы — через
|
||||||
|
`executeCommand()`:
|
||||||
|
|
||||||
|
```php
|
||||||
|
Yii::$app->redis->set('foo', 'bar');
|
||||||
|
Yii::$app->redis->hset('hash', 'field', 'value');
|
||||||
|
Yii::$app->redis->expire('foo', 60);
|
||||||
|
Yii::$app->redis->executeCommand('CLIENT LIST');
|
||||||
|
Yii::$app->redis->executeCommand('GET', ['foo']);
|
||||||
|
```
|
||||||
|
|
||||||
|
### RedisCache — кеш моделей
|
||||||
|
|
||||||
|
Все значения кладутся `json_encode`-ом; «тип» ключа (первый сегмент до `:`)
|
||||||
|
регистрируется в Redis ключом `types:<тип>`.
|
||||||
|
|
||||||
|
```php
|
||||||
|
// одиночные ключи; $options: true → EX = params['redis']['livetime'] (default 15 мин),
|
||||||
|
// int → EX в секундах, null → без TTL
|
||||||
|
RedisCache::set('group:5', $attributes, true);
|
||||||
|
RedisCache::setModel('group:5', $group); // $group->attributes
|
||||||
|
RedisCache::get('group:5'); // false при промахе/выключенном кеше
|
||||||
|
RedisCache::getModel('group:5', Group::class);
|
||||||
|
|
||||||
|
// хеши (без TTL — живут до явной инвалидации)
|
||||||
|
RedisCache::hset('group_items:5', 'type:es:<md5>', $data);
|
||||||
|
RedisCache::hsetModel('group_items:5', 'sku:17', $sku);
|
||||||
|
RedisCache::hget('group_items:5', 'sku:17');
|
||||||
|
RedisCache::hgetModel('group_items:5', 'sku:17', Sku::class);
|
||||||
|
|
||||||
|
// массивы моделей, опционально с yii\data\Pagination:
|
||||||
|
// в field дописывается ":page:N:perPage:N:sort:X", в значение — блок ['page' => [...]]
|
||||||
|
RedisCache::hsetModelArray('group_items:5', 'type:es:' . $md5, $skus, $pagination);
|
||||||
|
$skus = RedisCache::hgetModelArray('group_items:5', 'type:es:' . $md5, Sku::class, $pagination);
|
||||||
|
// при попадании $pagination->totalCount/perPage/sort восстановлены из кеша, а
|
||||||
|
// каждой модели с полем $ids проставлен список id страницы (пакетная предзагрузка)
|
||||||
|
```
|
||||||
|
|
||||||
|
Аналоги без хешей: `setModelArray()` / `getModelArray()`.
|
||||||
|
|
||||||
|
### Инвалидация
|
||||||
|
|
||||||
|
```php
|
||||||
|
RedisCache::hdel('group_items:5', $field);
|
||||||
|
RedisCache::del('group:5');
|
||||||
|
RedisCache::delete('group_items:5', ['type:es:*']); // hscan по полям хеша
|
||||||
|
RedisCache::deleteAll('group:5');
|
||||||
|
RedisCache::deleteType('sku_price'); // удалить всё пространство ключей "sku_price*" + types:-запись
|
||||||
|
RedisCache::getKeyTypes(); // ['*', ...типы из types:*] — для страниц управления кешем
|
||||||
|
```
|
||||||
|
|
||||||
|
### Отложенное удаление
|
||||||
|
|
||||||
|
В консольных воркерах (`catalog-app/commands/Controller.php`) включается режим,
|
||||||
|
при котором `del`/`hdel` не бьют по Redis сразу, а пишут «теневую» запись в
|
||||||
|
`del:<key>` (field `'-'` или имя поля) с меткой `time() + keysDeleteTime`
|
||||||
|
(30 с). Реальную очистку делает `RedisCache::oldCacheDelete()` — её стоит
|
||||||
|
запускать из cron:
|
||||||
|
|
||||||
|
```php
|
||||||
|
RedisCache::setDeleteKeyValue(true); // del/hdel → очередь del:*
|
||||||
|
RedisCache::oldCacheDelete(); // вымыть просроченные из del:*
|
||||||
|
```
|
||||||
|
|
||||||
|
### Глобальный выключатель кеша
|
||||||
|
|
||||||
|
`RedisCache::setActive(false)` — `hset`/`set` ничего не пишут, `hget`/`get`
|
||||||
|
всегда `false` (используется для резёва индексов и замеров холодного пути;
|
||||||
|
в `catalog-app` включается из `.env` переменной `CACHE_ACTIVE` через
|
||||||
|
`CacheHelper::configureFromEnv()`).
|
||||||
|
|
||||||
|
## Известные особенности
|
||||||
|
|
||||||
|
- `RedisCache::set()` всегда возвращает `false` — результат записи не
|
||||||
|
проброшен; `setModel`/`setModelArray` наследуют это же поведение.
|
||||||
|
- `hset` никогда не ставит TTL: хеши живут до явной инвалидации (в
|
||||||
|
`catalog-app` — `CacheHelper::deleteAll("group_items:<groupId>")` в
|
||||||
|
`Product::afterSave`).
|
||||||
|
- Ключи `types:*` тоже без TTL и никогда не чистятся, кроме случая
|
||||||
|
`deleteType()`.
|
||||||
|
- В `RedisCache::delete()` массив `$patterns` обходится вложенным циклом (N²
|
||||||
|
проходов hscan по одному хешу).
|
||||||
|
- Ключи, полученные из `keys()`/`hscan`, содержат `prefix`, поэтому `deleteType`
|
||||||
|
и `oldCacheDelete` срезают его через `str_replace(self::prefix(), '', ...)` —
|
||||||
|
при пустом префиксе работает «случайно корректно».
|
||||||
|
- В `SentinelConnection::connectToSentinel()` при пустом хосте бросается
|
||||||
|
необъявленный `\ConfigurationException` (не импортирован) — вместо внятной
|
||||||
|
ошибки конфигурации будет `Error: Class not found`; `slaves` подключаются
|
||||||
|
eagerly и не перепроверяются при смене topology.
|
||||||
|
- Белый список рабских команд — намеренно короткий (`GET`, `HGET`), новые
|
||||||
|
чтения на рабов добавляются правкой `$redisSlaveCommands` у компонента.
|
||||||
|
|
||||||
|
## Ветки репозитория
|
||||||
|
|
||||||
|
`master` — основная линия; Sentinel-поддержка (`SentinelConnection`) — ветка
|
||||||
|
`redis-sentinel`, на неё указывает текущий checkout приложений; исторические —
|
||||||
|
`old`, `preadis` (эксперимент с predis).
|
||||||
+85
-190
@@ -3,35 +3,34 @@
|
|||||||
namespace dominion\cache;
|
namespace dominion\cache;
|
||||||
|
|
||||||
use Yii;
|
use Yii;
|
||||||
use Redis;
|
|
||||||
use yii\console\Exception;
|
|
||||||
|
|
||||||
class RedisCache
|
class RedisCache
|
||||||
{
|
{
|
||||||
protected static $redis;
|
|
||||||
/**
|
/**
|
||||||
* используется для отключения кеширования
|
* используется для отключения кеширования
|
||||||
* например при реиндексе или дебаге
|
* например при реиндексе или дебаге
|
||||||
* @var type
|
* @var type
|
||||||
*/
|
*/
|
||||||
protected static $active = true;
|
protected static $active = true;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* время жизни кеша в секундах
|
* время жизни кеша в секундах
|
||||||
* @var int
|
* @var int
|
||||||
*/
|
*/
|
||||||
protected static $livetime = 300;
|
protected static $livetime;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* начальная директория для кеша в редисе
|
* начальная директория для кеша в редисе
|
||||||
* @var type
|
* @var type
|
||||||
*/
|
*/
|
||||||
protected static $prefix = '';
|
protected static $prefix;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Время чкрез ктр удалить кешь
|
* Время чкрез ктр удалить кешь
|
||||||
* @var int
|
* @var int
|
||||||
*/
|
*/
|
||||||
protected static $keysDeleteTime = 30;
|
protected static $keysDeleteTime = 30;
|
||||||
|
|
||||||
protected static $setDeleteKey = false;
|
protected static $setDeleteKey = false;
|
||||||
|
|
||||||
public static function setActive($active)
|
public static function setActive($active)
|
||||||
@@ -49,93 +48,57 @@ class RedisCache
|
|||||||
self::$setDeleteKey = $setDeleteKey;
|
self::$setDeleteKey = $setDeleteKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function connection($reConnect = false)
|
protected static function livetime()
|
||||||
{
|
{
|
||||||
if(!self::$redis || $reConnect)
|
if (!self::$livetime)
|
||||||
{
|
{
|
||||||
if(empty(Yii::$app->params['redis'])) {
|
self::$livetime = isset(Yii::$app->params['redis'], Yii::$app->params['redis']['livetime']) ? (int) Yii::$app->params['redis']['livetime'] : 15*60;
|
||||||
throw new Exception('Отсутствует конфигурация для redis');
|
|
||||||
}
|
|
||||||
if(empty(Yii::$app->params['redis']['host'])) {
|
|
||||||
throw new Exception('Отсутствует конфигурация для redis host');
|
|
||||||
}
|
|
||||||
if(empty(Yii::$app->params['redis']['port'])) {
|
|
||||||
throw new Exception('Отсутствует конфигурация для redis port');
|
|
||||||
}
|
|
||||||
if(empty(Yii::$app->params['redis']['prefix'])) {
|
|
||||||
throw new Exception('Отсутствует конфигурация для redis prefix');
|
|
||||||
}
|
|
||||||
|
|
||||||
$redis = new Redis;
|
|
||||||
$redis->connect(Yii::$app->params['redis']['host'], Yii::$app->params['redis']['port']);
|
|
||||||
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_IGBINARY);
|
|
||||||
$redis->setOption(Redis::OPT_PREFIX, Yii::$app->params['redis']['prefix']);
|
|
||||||
$redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);
|
|
||||||
|
|
||||||
self::$redis = $redis;
|
|
||||||
self::$livetime = isset(Yii::$app->params['redis']['livetime']) ? (int)Yii::$app->params['redis']['livetime'] : self::$livetime;
|
|
||||||
self::$prefix = Yii::$app->params['redis']['prefix'];
|
|
||||||
}
|
}
|
||||||
return self::$redis;
|
return self::$livetime;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function hdel($key, $value, $connect)
|
protected static function prefix()
|
||||||
{
|
{
|
||||||
if(self::$setDeleteKey)
|
if (!self::$prefix)
|
||||||
|
{
|
||||||
|
self::$prefix = isset(Yii::$app->redis->parameters, Yii::$app->redis->parameters['prefix']) ? Yii::$app->redis->parameters['prefix'] : '';
|
||||||
|
}
|
||||||
|
return self::$prefix;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function hdel($key, $value)
|
||||||
|
{
|
||||||
|
if (self::$setDeleteKey)
|
||||||
{
|
{
|
||||||
self::addDeleteKey($key, $value);
|
self::addDeleteKey($key, $value);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$prefix = self::$prefix;
|
Yii::$app->redis->hdel($key, $value);
|
||||||
$raw = "HDEL {$prefix}{$key} {$value}";
|
|
||||||
Yii::beginProfile($raw, 'yii\db\Command::query');
|
|
||||||
$connect->hdel($key, $value);
|
|
||||||
Yii::endProfile($raw, 'yii\db\Command::query');
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function del($key, $realDelete = false)
|
public static function del($key, $realDelete = false)
|
||||||
{
|
{
|
||||||
if(self::$setDeleteKey && !$realDelete)
|
if (self::$setDeleteKey && !$realDelete)
|
||||||
{
|
{
|
||||||
self::addDeleteKey($key);
|
self::addDeleteKey($key);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
$prefix = self::$prefix;
|
Yii::$app->redis->del($key);
|
||||||
$raw = "DEL {$prefix}{$key}";
|
|
||||||
Yii::beginProfile($raw, 'yii\db\Command::query');
|
|
||||||
try
|
|
||||||
{
|
|
||||||
self::connection()->del($key);
|
|
||||||
}
|
|
||||||
catch (\Exception $exc)
|
|
||||||
{
|
|
||||||
self::connection(true)->del($key);
|
|
||||||
}
|
|
||||||
Yii::endProfile($raw, 'yii\db\Command::query');
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function hset($key, $field, $value)
|
public static function hset($key, $field, $value)
|
||||||
{
|
{
|
||||||
$result = false;
|
$output = false;
|
||||||
if(self::getActive())
|
if(self::getActive())
|
||||||
{
|
{
|
||||||
$prefix = self::$prefix;
|
Yii::$app->redis->set('types:'.explode(':', $key)[0], 1);
|
||||||
$raw = "HSET {$prefix}{$key} {$field}";
|
$output = Yii::$app->redis->hset($key, $field, json_encode($value));
|
||||||
Yii::beginProfile($raw, 'yii\db\Command::query');
|
|
||||||
try
|
|
||||||
{
|
|
||||||
$result = self::connection()->hset($key, $field, $value);
|
|
||||||
}
|
|
||||||
catch (\Exception $exc)
|
|
||||||
{
|
|
||||||
$result = self::connection(true)->hset($key, $field, $value);
|
|
||||||
}
|
|
||||||
Yii::endProfile($raw, 'yii\db\Command::query');
|
|
||||||
}
|
}
|
||||||
return $result;
|
return $output;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function hsetModel($key, $field, $model)
|
public static function hsetModel($key, $field, $model)
|
||||||
@@ -158,7 +121,7 @@ class RedisCache
|
|||||||
{
|
{
|
||||||
$values[] = $model->attributes;
|
$values[] = $model->attributes;
|
||||||
}
|
}
|
||||||
if($page)
|
if ($page)
|
||||||
{
|
{
|
||||||
$values['page'] = [
|
$values['page'] = [
|
||||||
'totalCount' => $page->totalCount,
|
'totalCount' => $page->totalCount,
|
||||||
@@ -172,23 +135,12 @@ class RedisCache
|
|||||||
|
|
||||||
public static function hget($key, $field)
|
public static function hget($key, $field)
|
||||||
{
|
{
|
||||||
$result = false;
|
$output = false;
|
||||||
if(self::getActive())
|
if(self::getActive())
|
||||||
{
|
{
|
||||||
$prefix = self::$prefix;
|
$output = json_decode(Yii::$app->redis->hget($key, $field), true);
|
||||||
$raw = "HGET {$prefix}{$key} {$field}";
|
|
||||||
Yii::beginProfile($raw, 'yii\db\Command::query');
|
|
||||||
try
|
|
||||||
{
|
|
||||||
$result = self::connection()->hget($key, $field);
|
|
||||||
}
|
|
||||||
catch (\Exception $exc)
|
|
||||||
{
|
|
||||||
$result = self::connection(true)->hget($key, $field);
|
|
||||||
}
|
|
||||||
Yii::endProfile($raw, 'yii\db\Command::query');
|
|
||||||
}
|
}
|
||||||
return $result;
|
return $output === null ? false : $output;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function hgetModel($key, $field, $className)
|
public static function hgetModel($key, $field, $className)
|
||||||
@@ -199,19 +151,19 @@ class RedisCache
|
|||||||
|
|
||||||
public static function hgetModelArray($key, $field, $className, $page = null)
|
public static function hgetModelArray($key, $field, $className, $page = null)
|
||||||
{
|
{
|
||||||
if($page)
|
if ($page)
|
||||||
{
|
{
|
||||||
$field .= ":page:{$page->page}:perPage:{$page->perPage}:sort:{$page->sort}";
|
$field .= ":page:{$page->page}:perPage:{$page->perPage}:sort:{$page->sort}";
|
||||||
}
|
}
|
||||||
$values = self::hget($key, $field);
|
$values = self::hget($key, $field);
|
||||||
if($values === false)
|
if ($values === false)
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
$ids = [];
|
$ids = [];
|
||||||
foreach ($values as $keyVal => $value)
|
foreach ($values as $keyVal => $value)
|
||||||
{
|
{
|
||||||
if($keyVal !== 'page' && isset($value['id']))
|
if ($keyVal !== 'page' && isset($value['id']))
|
||||||
{
|
{
|
||||||
$ids[] = $value['id'];
|
$ids[] = $value['id'];
|
||||||
}
|
}
|
||||||
@@ -219,9 +171,9 @@ class RedisCache
|
|||||||
$output = [];
|
$output = [];
|
||||||
foreach ($values as $keyVal => $value)
|
foreach ($values as $keyVal => $value)
|
||||||
{
|
{
|
||||||
if($keyVal === 'page')
|
if ($keyVal === 'page')
|
||||||
{
|
{
|
||||||
if($page)
|
if ($page)
|
||||||
{
|
{
|
||||||
$page->setMeta($value['totalCount'], $value['perPage']);
|
$page->setMeta($value['totalCount'], $value['perPage']);
|
||||||
$page->sort = $value['sort'];
|
$page->sort = $value['sort'];
|
||||||
@@ -230,7 +182,7 @@ class RedisCache
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
$model = new $className($value);
|
$model = new $className($value);
|
||||||
if(isset($model->ids))
|
if (isset($model->ids))
|
||||||
{
|
{
|
||||||
$model->ids = $ids;
|
$model->ids = $ids;
|
||||||
}
|
}
|
||||||
@@ -242,29 +194,27 @@ class RedisCache
|
|||||||
|
|
||||||
public static function delete($key, array $patterns)
|
public static function delete($key, array $patterns)
|
||||||
{
|
{
|
||||||
if(self::getActive())
|
if (self::getActive())
|
||||||
{
|
{
|
||||||
$prefix = self::$prefix;
|
foreach ($patterns as $pattern)
|
||||||
$connect = self::connection();
|
|
||||||
foreach($patterns as $pattern)
|
|
||||||
{
|
{
|
||||||
$cursor = NULL;
|
$cursor = NULL;
|
||||||
foreach ($patterns as $pattern)
|
foreach ($patterns as $pattern)
|
||||||
{
|
{
|
||||||
$arKeys = [];
|
$arKeys = [];
|
||||||
$raw = "HSCAN {$prefix}{$key} {$cursor} MATCH {$pattern}";
|
$count = 1000;
|
||||||
Yii::beginProfile($raw, 'yii\db\Command::query');
|
while ($values = Yii::$app->redis->hscan($key, $cursor, $pattern, $count))
|
||||||
while($values = $connect->hscan($key, $cursor, $pattern))
|
|
||||||
{
|
{
|
||||||
foreach($values as $vkey => $value)
|
foreach ($values as $vkey => $value)
|
||||||
{
|
{
|
||||||
$arKeys[] = $vkey;
|
$arKeys[] = $vkey;
|
||||||
}
|
}
|
||||||
|
if(count($values) < $count)
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
Yii::endProfile($raw, 'yii\db\Command::query');
|
foreach ($arKeys as $value)
|
||||||
foreach($arKeys as $value)
|
|
||||||
{
|
{
|
||||||
self::hdel($key, $value, $connect);
|
self::hdel($key, $value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -278,7 +228,7 @@ class RedisCache
|
|||||||
*/
|
*/
|
||||||
public static function deleteAll($key, $realDelete = false)
|
public static function deleteAll($key, $realDelete = false)
|
||||||
{
|
{
|
||||||
if(self::getActive())
|
if (self::getActive())
|
||||||
{
|
{
|
||||||
self::del($key, $realDelete);
|
self::del($key, $realDelete);
|
||||||
}
|
}
|
||||||
@@ -286,23 +236,12 @@ class RedisCache
|
|||||||
|
|
||||||
public static function getKeyTypes()
|
public static function getKeyTypes()
|
||||||
{
|
{
|
||||||
$prefix = self::$prefix;
|
$result = Yii::$app->redis->keys('types:*');
|
||||||
$raw = "KEYS {$prefix}*";
|
|
||||||
Yii::beginProfile($raw, 'yii\db\Command::query');
|
|
||||||
try
|
|
||||||
{
|
|
||||||
$result = self::connection()->keys('*');
|
|
||||||
}
|
|
||||||
catch (\Exception $exc)
|
|
||||||
{
|
|
||||||
$result = self::connection(true)->keys('*');
|
|
||||||
}
|
|
||||||
Yii::endProfile($raw, 'yii\db\Command::query');
|
|
||||||
$output = ['*'];
|
$output = ['*'];
|
||||||
foreach ($result as $val)
|
foreach ($result as $val)
|
||||||
{
|
{
|
||||||
$arVal = explode(':', $val);
|
$arVal = explode('types:', $val);
|
||||||
if(isset($arVal[1]) && !in_array($arVal[1], $output))
|
if (isset($arVal[1]) && !in_array($arVal[1], $output))
|
||||||
{
|
{
|
||||||
$output[] = $arVal[1];
|
$output[] = $arVal[1];
|
||||||
}
|
}
|
||||||
@@ -318,25 +257,14 @@ class RedisCache
|
|||||||
*/
|
*/
|
||||||
public static function deleteType($type)
|
public static function deleteType($type)
|
||||||
{
|
{
|
||||||
if(self::getActive())
|
if (self::getActive())
|
||||||
{
|
{
|
||||||
self::deleteAll($type);
|
self::deleteAll($type);
|
||||||
$type = $type == "*" ? "*" : "{$type}:*";
|
$type = $type == "*" ? "*" : "{$type}:*";
|
||||||
$prefix = self::$prefix;
|
$result = Yii::$app->redis->keys($type);
|
||||||
$raw = "KEYS {$prefix}{$type}";
|
|
||||||
Yii::beginProfile($raw, 'yii\db\Command::query');
|
|
||||||
try
|
|
||||||
{
|
|
||||||
$result = self::connection()->keys($type);
|
|
||||||
}
|
|
||||||
catch (\Exception $exc)
|
|
||||||
{
|
|
||||||
$result = self::connection(true)->keys($type);
|
|
||||||
}
|
|
||||||
Yii::endProfile($raw, 'yii\db\Command::query');
|
|
||||||
foreach ($result as $val)
|
foreach ($result as $val)
|
||||||
{
|
{
|
||||||
self::deleteAll(str_replace($prefix, '', $val));
|
self::deleteAll(str_replace(self::prefix(), '', $val));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
@@ -345,34 +273,18 @@ class RedisCache
|
|||||||
public static function set($key, $value, $options = null)
|
public static function set($key, $value, $options = null)
|
||||||
{
|
{
|
||||||
$result = false;
|
$result = false;
|
||||||
if(self::getActive())
|
if (self::getActive())
|
||||||
{
|
{
|
||||||
if($options === true)
|
if ($options === true)
|
||||||
{
|
{
|
||||||
$options = ['EX' => self::$livetime];
|
$options = ['EX' => self::livetime()];
|
||||||
}
|
}
|
||||||
elseif(is_int($options))
|
elseif (is_int($options))
|
||||||
{
|
{
|
||||||
$options = ['EX' => $options];
|
$options = ['EX' => $options];
|
||||||
}
|
}
|
||||||
$addStr = '';
|
Yii::$app->redis->set('types:'. explode(':', $key)[0], 1);
|
||||||
foreach((array)$options as $okey => $oval)
|
Yii::$app->redis->set($key, json_encode($value), $options);
|
||||||
{
|
|
||||||
$addStr .= "{$okey} {$oval}";
|
|
||||||
}
|
|
||||||
$prefix = self::$prefix;
|
|
||||||
$json = json_encode($value);
|
|
||||||
$raw = "SET {$prefix}{$key} {$json} {$addStr}";
|
|
||||||
Yii::beginProfile($raw, 'yii\db\Command::query');
|
|
||||||
try
|
|
||||||
{
|
|
||||||
$result = self::connection()->set($key, $json, $options);
|
|
||||||
}
|
|
||||||
catch (\Exception $exc)
|
|
||||||
{
|
|
||||||
$result = self::connection(true)->set($key, $json, $options);
|
|
||||||
}
|
|
||||||
Yii::endProfile($raw, 'yii\db\Command::query');
|
|
||||||
}
|
}
|
||||||
return $result;
|
return $result;
|
||||||
}
|
}
|
||||||
@@ -389,7 +301,7 @@ class RedisCache
|
|||||||
{
|
{
|
||||||
$values[] = $model->attributes;
|
$values[] = $model->attributes;
|
||||||
}
|
}
|
||||||
if($page)
|
if ($page)
|
||||||
{
|
{
|
||||||
$values['page'] = [
|
$values['page'] = [
|
||||||
'totalCount' => $page->totalCount,
|
'totalCount' => $page->totalCount,
|
||||||
@@ -403,22 +315,11 @@ class RedisCache
|
|||||||
public static function get(string $key)
|
public static function get(string $key)
|
||||||
{
|
{
|
||||||
$result = false;
|
$result = false;
|
||||||
if(self::getActive())
|
if (self::getActive())
|
||||||
{
|
{
|
||||||
$prefix = self::$prefix;
|
$result = json_decode(Yii::$app->redis->get($key), true);
|
||||||
$raw = "GET {$prefix}{$key}";
|
|
||||||
Yii::beginProfile($raw, 'yii\db\Command::query');
|
|
||||||
try
|
|
||||||
{
|
|
||||||
$result = self::connection()->get($key);
|
|
||||||
}
|
|
||||||
catch (\Exception $exc)
|
|
||||||
{
|
|
||||||
$result = self::connection(true)->get($key);
|
|
||||||
}
|
|
||||||
Yii::endProfile($raw, 'yii\db\Command::query');
|
|
||||||
}
|
}
|
||||||
return $result ? json_decode($result, true) : $result;
|
return $result === null ? false : $result;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function getModel($key, $className)
|
public static function getModel($key, $className)
|
||||||
@@ -430,14 +331,14 @@ class RedisCache
|
|||||||
public static function getModelArray($key, $className, $page = null)
|
public static function getModelArray($key, $className, $page = null)
|
||||||
{
|
{
|
||||||
$values = self::get($key);
|
$values = self::get($key);
|
||||||
if($values === false)
|
if ($values === false)
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
$ids = [];
|
$ids = [];
|
||||||
foreach ($values as $keyVal => $value)
|
foreach ($values as $keyVal => $value)
|
||||||
{
|
{
|
||||||
if($keyVal !== 'page' && isset($value['id']))
|
if ($keyVal !== 'page' && isset($value['id']))
|
||||||
{
|
{
|
||||||
$ids[] = $value['id'];
|
$ids[] = $value['id'];
|
||||||
}
|
}
|
||||||
@@ -445,9 +346,9 @@ class RedisCache
|
|||||||
$output = [];
|
$output = [];
|
||||||
foreach ($values as $keyVal => $value)
|
foreach ($values as $keyVal => $value)
|
||||||
{
|
{
|
||||||
if($keyVal === 'page')
|
if ($keyVal === 'page')
|
||||||
{
|
{
|
||||||
if($page)
|
if ($page)
|
||||||
{
|
{
|
||||||
$page->setMeta($value['totalCount'], $value['perPage']);
|
$page->setMeta($value['totalCount'], $value['perPage']);
|
||||||
$page->sort = $value['sort'];
|
$page->sort = $value['sort'];
|
||||||
@@ -456,7 +357,7 @@ class RedisCache
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
$model = new $className($value);
|
$model = new $className($value);
|
||||||
if(isset($model->ids))
|
if (isset($model->ids))
|
||||||
{
|
{
|
||||||
$model->ids = $ids;
|
$model->ids = $ids;
|
||||||
}
|
}
|
||||||
@@ -474,55 +375,49 @@ class RedisCache
|
|||||||
*/
|
*/
|
||||||
public static function addDeleteKey($key, $field = '-')
|
public static function addDeleteKey($key, $field = '-')
|
||||||
{
|
{
|
||||||
return self::hset('del:'.$key, $field, time() + self::$keysDeleteTime);
|
return self::hset('del:' . $key, $field, time() + self::$keysDeleteTime);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Удаляет устаревший кеш
|
* Удаляет устаревший кеш
|
||||||
* @return type
|
* @return type
|
||||||
*/
|
*/
|
||||||
public static function oldCacheDelete()
|
public static function oldCacheDelete()
|
||||||
{
|
{
|
||||||
$connect = self::connection();
|
$result = Yii::$app->redis->keys('del:*');
|
||||||
$prefix = self::$prefix;
|
|
||||||
$raw = "KEYS {$prefix}del:*";
|
|
||||||
Yii::beginProfile($raw, 'yii\db\Command::query');
|
|
||||||
$result = $connect->keys('del:*');
|
|
||||||
Yii::endProfile($raw, 'yii\db\Command::query');
|
|
||||||
foreach ($result as $val)
|
foreach ($result as $val)
|
||||||
{
|
{
|
||||||
$cursor = null;
|
$cursor = null;
|
||||||
//$key = str_replace("{$prefix}del:", '', $val);
|
$key = str_replace(self::prefix(), '', $val);
|
||||||
$key = str_replace($prefix, '', $val);
|
|
||||||
$pattern = '*';
|
$pattern = '*';
|
||||||
$arKeys = [];
|
$arKeys = [];
|
||||||
$raw = "HSCAN {$prefix}{$key} {$cursor} MATCH {$pattern}";
|
$count = 1000;
|
||||||
Yii::beginProfile($raw, 'yii\db\Command::query');
|
while ($values = Yii::$app->redis->hscan($key, $cursor, $pattern, $count))
|
||||||
while($values = $connect->hscan($key, $cursor, $pattern))
|
|
||||||
{
|
{
|
||||||
foreach($values as $vkey => $value)
|
foreach ($values as $vkey => $value)
|
||||||
{
|
{
|
||||||
if($value < time())
|
if ($value < time())
|
||||||
{
|
{
|
||||||
$arKeys[] = $vkey;
|
$arKeys[] = $vkey;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if(count($values) < $count)
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
$keyCache = str_replace("{$prefix}del:", '', $val);
|
$keyCache = str_replace(self::prefix() . "del:", '', $val);
|
||||||
Yii::endProfile($raw, 'yii\db\Command::query');
|
foreach ($arKeys as $value)
|
||||||
foreach($arKeys as $value)
|
|
||||||
{
|
{
|
||||||
self::$setDeleteKey = false;
|
self::$setDeleteKey = false;
|
||||||
if($value == '-')
|
if ($value == '-')
|
||||||
{
|
{
|
||||||
self::del($keyCache, $connect);
|
self::del($keyCache);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
self::hdel($keyCache, $value, $connect);
|
self::hdel($keyCache, $value);
|
||||||
}
|
}
|
||||||
self::hdel($key, $value, $connect);
|
self::hdel($key, $value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace dominion\cache;
|
||||||
|
|
||||||
|
use Yii;
|
||||||
|
use yii\helpers\Inflector;
|
||||||
|
use Redis;
|
||||||
|
use RedisException;
|
||||||
|
use RedisSentinel;
|
||||||
|
|
||||||
|
class SentinelConnection extends Connection
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Команды достапные на любой ноде master или slave
|
||||||
|
* @var array
|
||||||
|
*/
|
||||||
|
public $redisSlaveCommands = [
|
||||||
|
'GET',
|
||||||
|
'HGET',
|
||||||
|
//нужно перечислить все, но пока так
|
||||||
|
];
|
||||||
|
|
||||||
|
public $slaves = [];
|
||||||
|
|
||||||
|
public function executeCommand($name, $params = [])
|
||||||
|
{
|
||||||
|
$this->open();
|
||||||
|
Yii::debug("Executing Redis Command: {$name} " . var_export($params, true), __METHOD__);
|
||||||
|
|
||||||
|
$redis = $this->redis; //мастер
|
||||||
|
$redisCommand = strtoupper(Inflector::camel2words($name, false));
|
||||||
|
if (in_array($redisCommand, $this->redisSlaveCommands))
|
||||||
|
{
|
||||||
|
if(!empty($this->slaves))
|
||||||
|
{
|
||||||
|
//читаем из произвольного раба
|
||||||
|
$redis = $this->slaves[array_rand($this->slaves)];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $redis->{$name}(...$params);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function isValidServer(mixed $server): bool
|
||||||
|
{
|
||||||
|
return is_array($server) && isset($server['ip']) && isset($server['port']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function createClient(array $config): Redis
|
||||||
|
{
|
||||||
|
$service = $config['sentinel_service'] ?? 'mymaster';
|
||||||
|
|
||||||
|
$hosts = is_array($config['sentinel_host']) ? $config['sentinel_host'] : [$config['sentinel_host']];
|
||||||
|
foreach ($hosts as $host)
|
||||||
|
{
|
||||||
|
$newConfig = $config;
|
||||||
|
$newConfig['sentinel_host'] = $host;
|
||||||
|
$sentinel = $this->connectToSentinel($newConfig);
|
||||||
|
|
||||||
|
if ($sentinel->ping())
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$master = $sentinel->master($service);
|
||||||
|
if (!$this->isValidServer($master))
|
||||||
|
{
|
||||||
|
throw new RedisException(sprintf("No master found for service '%s'.", $service));
|
||||||
|
}
|
||||||
|
$slaves = $sentinel->slaves($service);
|
||||||
|
foreach ($slaves as $slave)
|
||||||
|
{
|
||||||
|
if ($this->isValidServer($slave))
|
||||||
|
{
|
||||||
|
//могут быть проблемв из-за большого количества подключений
|
||||||
|
$this->slaves[] = parent::createClient(array_merge($config, [
|
||||||
|
'host' => $slave['ip'],
|
||||||
|
'port' => $slave['port'],
|
||||||
|
]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return parent::createClient(array_merge($config, [
|
||||||
|
'host' => $master['ip'],
|
||||||
|
'port' => $master['port'],
|
||||||
|
]));
|
||||||
|
}
|
||||||
|
|
||||||
|
private function connectToSentinel(array $config): RedisSentinel
|
||||||
|
{
|
||||||
|
$host = $config['sentinel_host'] ?? '';
|
||||||
|
$port = $config['sentinel_port'] ?? 26379;
|
||||||
|
$timeout = $config['sentinel_timeout'] ?? 0.2;
|
||||||
|
$persistent = $config['sentinel_persistent'] ?? null;
|
||||||
|
$retryInterval = $config['sentinel_retry_interval'] ?? 0;
|
||||||
|
$readTimeout = $config['sentinel_read_timeout'] ?? 0;
|
||||||
|
$username = $config['sentinel_username'] ?? '';
|
||||||
|
$password = $config['sentinel_password'] ?? '';
|
||||||
|
$ssl = $config['sentinel_ssl'] ?? null;
|
||||||
|
|
||||||
|
if (strlen(trim($host)) === 0)
|
||||||
|
{
|
||||||
|
throw new ConfigurationException('No host has been specified for the Redis Sentinel connection.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$auth = null;
|
||||||
|
if (strlen(trim($username)) !== 0 && strlen(trim($password)) !== 0)
|
||||||
|
{
|
||||||
|
$auth = [$username, $password];
|
||||||
|
}
|
||||||
|
elseif (strlen(trim($password)) !== 0)
|
||||||
|
{
|
||||||
|
$auth = $password;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (version_compare(phpversion('redis'), '6.0', '>='))
|
||||||
|
{
|
||||||
|
$options = [
|
||||||
|
'host' => $host,
|
||||||
|
'port' => $port,
|
||||||
|
'connectTimeout' => $timeout,
|
||||||
|
'persistent' => $persistent,
|
||||||
|
'retryInterval' => $retryInterval,
|
||||||
|
'readTimeout' => $readTimeout,
|
||||||
|
];
|
||||||
|
|
||||||
|
if ($auth !== null)
|
||||||
|
{
|
||||||
|
$options['auth'] = $auth;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (version_compare(phpversion('redis'), '6.1', '>=') && $ssl !== null)
|
||||||
|
{
|
||||||
|
$options['ssl'] = $ssl;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new RedisSentinel($options);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($auth !== null)
|
||||||
|
{
|
||||||
|
/** @noinspection PhpMethodParametersCountMismatchInspection */
|
||||||
|
return new RedisSentinel($host, $port, $timeout, $persistent, $retryInterval, $readTimeout, $auth);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new RedisSentinel($host, $port, $timeout, $persistent, $retryInterval, $readTimeout);
|
||||||
|
}
|
||||||
|
}
|
||||||
+172
@@ -0,0 +1,172 @@
|
|||||||
|
<?php
|
||||||
|
/**
|
||||||
|
* @link https://www.yiiframework.com/
|
||||||
|
* @copyright Copyright (c) 2008 Yii Software LLC
|
||||||
|
* @license https://www.yiiframework.com/license/
|
||||||
|
*/
|
||||||
|
|
||||||
|
namespace dominion\cache;
|
||||||
|
|
||||||
|
use Yii;
|
||||||
|
use yii\base\InvalidConfigException;
|
||||||
|
use yii\di\Instance;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Redis Session implements a session component using [redis](https://redis.io/) as the storage medium.
|
||||||
|
*
|
||||||
|
* Redis Session requires redis version 2.6.12 or higher to work properly.
|
||||||
|
*
|
||||||
|
* It needs to be configured with a redis [[Connection]] that is also configured as an application component.
|
||||||
|
* By default it will use the `redis` application component.
|
||||||
|
*
|
||||||
|
* To use redis Session as the session application component, configure the application as follows,
|
||||||
|
*
|
||||||
|
* ~~~
|
||||||
|
* [
|
||||||
|
* 'components' => [
|
||||||
|
* 'session' => [
|
||||||
|
* 'class' => 'yii\redis\Session',
|
||||||
|
* 'redis' => [
|
||||||
|
* 'hostname' => 'localhost',
|
||||||
|
* 'port' => 6379,
|
||||||
|
* 'database' => 0,
|
||||||
|
* ]
|
||||||
|
* ],
|
||||||
|
* ],
|
||||||
|
* ]
|
||||||
|
* ~~~
|
||||||
|
*
|
||||||
|
* Or if you have configured the redis [[Connection]] as an application component, the following is sufficient:
|
||||||
|
*
|
||||||
|
* ~~~
|
||||||
|
* [
|
||||||
|
* 'components' => [
|
||||||
|
* 'session' => [
|
||||||
|
* 'class' => 'yii\redis\Session',
|
||||||
|
* // 'redis' => 'redis' // id of the connection application component
|
||||||
|
* ],
|
||||||
|
* ],
|
||||||
|
* ]
|
||||||
|
* ~~~
|
||||||
|
*
|
||||||
|
* @property-read bool $useCustomStorage Whether to use custom storage.
|
||||||
|
*
|
||||||
|
* @author Carsten Brandt <mail@cebe.cc>
|
||||||
|
* @since 2.0
|
||||||
|
*/
|
||||||
|
class Session extends \yii\web\Session
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @var Connection|string|array the Redis [[Connection]] object or the application component ID of the Redis [[Connection]].
|
||||||
|
* This can also be an array that is used to create a redis [[Connection]] instance in case you do not want do configure
|
||||||
|
* redis connection as an application component.
|
||||||
|
* After the Session object is created, if you want to change this property, you should only assign it
|
||||||
|
* with a Redis [[Connection]] object.
|
||||||
|
*/
|
||||||
|
public $redis = 'redis';
|
||||||
|
/**
|
||||||
|
* @var string a string prefixed to every cache key so that it is unique. If not set,
|
||||||
|
* it will use a prefix generated from [[Application::id]]. You may set this property to be an empty string
|
||||||
|
* if you don't want to use key prefix. It is recommended that you explicitly set this property to some
|
||||||
|
* static value if the cached data needs to be shared among multiple applications.
|
||||||
|
*/
|
||||||
|
public $keyPrefix;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initializes the redis Session component.
|
||||||
|
* This method will initialize the [[redis]] property to make sure it refers to a valid redis connection.
|
||||||
|
* @throws InvalidConfigException if [[redis]] is invalid.
|
||||||
|
*/
|
||||||
|
public function init()
|
||||||
|
{
|
||||||
|
$this->redis = Instance::ensure($this->redis, Connection::className());
|
||||||
|
if ($this->keyPrefix === null) {
|
||||||
|
$this->keyPrefix = substr(md5(Yii::$app->id), 0, 5);
|
||||||
|
}
|
||||||
|
parent::init();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a value indicating whether to use custom session storage.
|
||||||
|
* This method overrides the parent implementation and always returns true.
|
||||||
|
* @return bool whether to use custom storage.
|
||||||
|
*/
|
||||||
|
public function getUseCustomStorage()
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Session open handler.
|
||||||
|
* @internal Do not call this method directly.
|
||||||
|
* @param string $savePath session save path
|
||||||
|
* @param string $sessionName session name
|
||||||
|
* @return bool whether session is opened successfully
|
||||||
|
*/
|
||||||
|
public function openSession($savePath, $sessionName)
|
||||||
|
{
|
||||||
|
if ($this->getUseStrictMode()) {
|
||||||
|
$id = $this->getId();
|
||||||
|
if (!$this->redis->exists($this->calculateKey($id))) {
|
||||||
|
//This session id does not exist, mark it for forced regeneration
|
||||||
|
$this->_forceRegenerateId = $id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return parent::openSession($savePath, $sessionName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Session read handler.
|
||||||
|
* Do not call this method directly.
|
||||||
|
* @param string $id session ID
|
||||||
|
* @return string the session data
|
||||||
|
*/
|
||||||
|
public function readSession($id)
|
||||||
|
{
|
||||||
|
$data = $this->redis->get($this->calculateKey($id));
|
||||||
|
|
||||||
|
return $data === false || $data === null ? '' : $data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Session write handler.
|
||||||
|
* Do not call this method directly.
|
||||||
|
* @param string $id session ID
|
||||||
|
* @param string $data session data
|
||||||
|
* @return bool whether session write is successful
|
||||||
|
*/
|
||||||
|
public function writeSession($id, $data)
|
||||||
|
{
|
||||||
|
if ($this->getUseStrictMode() && $id === $this->_forceRegenerateId) {
|
||||||
|
//Ignore write when forceRegenerate is active for this id
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (bool) $this->redis->set($this->calculateKey($id), $data, ['EX' => $this->getTimeout()]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Session destroy handler.
|
||||||
|
* Do not call this method directly.
|
||||||
|
* @param string $id session ID
|
||||||
|
* @return bool whether session is destroyed successfully
|
||||||
|
*/
|
||||||
|
public function destroySession($id)
|
||||||
|
{
|
||||||
|
$this->redis->del($this->calculateKey($id));
|
||||||
|
// @see https://github.com/yiisoft/yii2-redis/issues/82
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates a unique key used for storing session data in cache.
|
||||||
|
* @param string $id session variable name
|
||||||
|
* @return string a safe cache key associated with the session variable name
|
||||||
|
*/
|
||||||
|
protected function calculateKey($id)
|
||||||
|
{
|
||||||
|
return $this->keyPrefix . md5(json_encode([__CLASS__, $id]));
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user