Class yii\redis\Connection

Inheritanceyii\redis\Connection » yii\base\Component
Implementsyii\redis\ConnectionInterface
Available since extension's version2.0
Source Code https://github.com/yiisoft/yii2-redis/blob/master/src/Connection.php

The redis connection class is used to establish a connection to a redis server.

By default it assumes there is a redis server running on localhost at port 6379 and uses the database number 0.

It is possible to connect to a redis server using $hostname and $port or using a $unixSocket.

It also supports the AUTH command of redis. When the server needs authentication, you can set the $password property to authenticate with the server after connect.

Public Properties

Hide inherited properties

Property Type Description Defined By
$connectionString string Socket connection string. yii\redis\Connection
$connectionTimeout float Timeout to use for connection to redis. yii\redis\Connection
$contextOptions array PHP context options which are used in the Redis connection stream. yii\redis\Connection
$dataTimeout float Timeout to use for redis socket when reading and writing data. yii\redis\Connection
$database integer The redis database to use. yii\redis\Connection
$driverName string Name of the DB driver. yii\redis\Connection
$hostname string The hostname or ip address to use for connecting to the redis server. yii\redis\Connection
$isActive boolean Whether the DB connection is established. yii\redis\Connection
$luaScriptBuilder yii\redis\LuaScriptBuilder yii\redis\Connection
$password string The password for establishing DB connection. yii\redis\Connection
$port integer The port to use for connecting to the redis server. yii\redis\Connection
$redirectConnectionString string If the query gets redirected, use this as the temporary new hostname yii\redis\Connection
$redisCommands array List of available redis commands. yii\redis\Connection
$retries integer The number of times a command execution should be retried when a connection failure occurs. yii\redis\Connection
$retryInterval integer The retry interval in microseconds to wait between retry. yii\redis\Connection
$scheme string The connection scheme used for connecting to the redis server. yii\redis\Connection
$socket resource|false yii\redis\Connection
$socketClientFlags integer Bitmask field which may be set to any combination of connection flags passed to stream_socket_client(). yii\redis\Connection
$unixSocket string The unix socket path (e.g. /var/run/redis/redis.sock) to use for connecting to the redis server. yii\redis\Connection
$useSSL boolean Send sockets over SSL protocol. yii\redis\Connection
$username string|null Username for establishing DB connection. yii\redis\Connection

Public Methods

Hide inherited methods

Method Description Defined By
__call() Allows issuing all supported commands via magic methods. yii\redis\Connection
__sleep() Closes the connection when this component is being serialized. yii\redis\Connection
close() Closes the currently active DB connection. yii\redis\Connection
executeCommand() Executes a redis command. yii\redis\Connection
getConnectionString() Return the connection string used to open a socket connection. During a redirect (cluster mode) this will be the target of the redirect. yii\redis\Connection
getDriverName() Returns the name of the DB driver for the current dsn. yii\redis\Connection
getIsActive() Returns a value indicating whether the DB connection is established. yii\redis\Connection
getLuaScriptBuilder() yii\redis\Connection
getSocket() Return the connection resource if a connection to the target has been established before, false otherwise. yii\redis\Connection
open() Establishes a DB connection. yii\redis\Connection

Protected Methods

Hide inherited methods

Method Description Defined By
initConnection() Initializes the DB connection. yii\redis\Connection
sendRawCommand() Sends RAW command string to the server. yii\redis\Connection

Events

Hide inherited events

Event Type Description Defined By
EVENT_AFTER_OPEN yii\redis\Event An event that is triggered after a DB connection is established yii\redis\Connection

Property Details

Hide inherited properties

$connectionString public property

Socket connection string.

public string $connectionString null
$connectionTimeout public property

Timeout to use for connection to redis. If not set the timeout set in php.ini will be used: ini_get("default_socket_timeout").

public float $connectionTimeout null
$contextOptions public property (available since version 2.0.15)

PHP context options which are used in the Redis connection stream.

See also https://www.php.net/manual/en/context.ssl.php.

public array $contextOptions = []
$dataTimeout public property

Timeout to use for redis socket when reading and writing data. If not set the php default value will be used.

public float $dataTimeout null
$database public property

The redis database to use. This is an integer value starting from 0. Defaults to 0. Since version 2.0.6 you can disable the SELECT command sent after connection by setting this property to null.

public integer $database 0
$driverName public property

Name of the DB driver.

public string $driverName null
$hostname public property

The hostname or ip address to use for connecting to the redis server. Defaults to 'localhost'. If $unixSocket is specified, hostname and $port will be ignored.

public string $hostname 'localhost'
$isActive public property

Whether the DB connection is established.

public boolean $isActive null
$luaScriptBuilder public property
$password public property

The password for establishing DB connection. Defaults to null meaning no AUTH command is sent. See https://redis.io/commands/auth

public string $password null
$port public property

The port to use for connecting to the redis server. Default port is 6379. If $unixSocket is specified, $hostname and port will be ignored.

public integer $port 6379
$redirectConnectionString public property (available since version 2.0.11)

If the query gets redirected, use this as the temporary new hostname

$redisCommands public property

List of available redis commands.

See also https://redis.io/commands.

public array $redisCommands = [
    
'APPEND',
    
'AUTH',
    
'BGREWRITEAOF',
    
'BGSAVE',
    
'BITCOUNT',
    
'BITFIELD',
    
'BITOP',
    
'BITPOS',
    
'BLPOP',
    
'BRPOP',
    
'BRPOPLPUSH',
    
'CLIENT KILL',
    
'CLIENT LIST',
    
'CLIENT GETNAME',
    
'CLIENT PAUSE',
    
'CLIENT REPLY',
    
'CLIENT SETNAME',
    
'CLUSTER ADDSLOTS',
    
'CLUSTER COUNTKEYSINSLOT',
    
'CLUSTER DELSLOTS',
    
'CLUSTER FAILOVER',
    
'CLUSTER FORGET',
    
'CLUSTER GETKEYSINSLOT',
    
'CLUSTER INFO',
    
'CLUSTER KEYSLOT',
    
'CLUSTER MEET',
    
'CLUSTER NODES',
    
'CLUSTER REPLICATE',
    
'CLUSTER RESET',
    
'CLUSTER SAVECONFIG',
    
'CLUSTER SETSLOT',
    
'CLUSTER SLAVES',
    
'CLUSTER SLOTS',
    
'COMMAND',
    
'COMMAND COUNT',
    
'COMMAND GETKEYS',
    
'COMMAND INFO',
    
'CONFIG GET',
    
'CONFIG REWRITE',
    
'CONFIG SET',
    
'CONFIG RESETSTAT',
    
'DBSIZE',
    
'DEBUG OBJECT',
    
'DEBUG SEGFAULT',
    
'DECR',
    
'DECRBY',
    
'DEL',
    
'DISCARD',
    
'DUMP',
    
'ECHO',
    
'EVAL',
    
'EVALSHA',
    
'EXEC',
    
'EXISTS',
    
'EXPIRE',
    
'EXPIREAT',
    
'FLUSHALL',
    
'FLUSHDB',
    
'GEOADD',
    
'GEOHASH',
    
'GEOPOS',
    
'GEODIST',
    
'GEORADIUS',
    
'GEORADIUSBYMEMBER',
    
'GET',
    
'GETBIT',
    
'GETRANGE',
    
'GETSET',
    
'HDEL',
    
'HEXISTS',
    
'HGET',
    
'HGETALL',
    
'HINCRBY',
    
'HINCRBYFLOAT',
    
'HKEYS',
    
'HLEN',
    
'HMGET',
    
'HMSET',
    
'HSET',
    
'HSETNX',
    
'HSTRLEN',
    
'HVALS',
    
'INCR',
    
'INCRBY',
    
'INCRBYFLOAT',
    
'INFO',
    
'KEYS',
    
'LASTSAVE',
    
'LINDEX',
    
'LINSERT',
    
'LLEN',
    
'LPOP',
    
'LPUSH',
    
'LPUSHX',
    
'LRANGE',
    
'LREM',
    
'LSET',
    
'LTRIM',
    
'MGET',
    
'MIGRATE',
    
'MONITOR',
    
'MOVE',
    
'MSET',
    
'MSETNX',
    
'MULTI',
    
'OBJECT',
    
'PERSIST',
    
'PEXPIRE',
    
'PEXPIREAT',
    
'PFADD',
    
'PFCOUNT',
    
'PFMERGE',
    
'PING',
    
'PSETEX',
    
'PSUBSCRIBE',
    
'PUBSUB',
    
'PTTL',
    
'PUBLISH',
    
'PUNSUBSCRIBE',
    
'QUIT',
    
'RANDOMKEY',
    
'READONLY',
    
'READWRITE',
    
'RENAME',
    
'RENAMENX',
    
'RESTORE',
    
'ROLE',
    
'RPOP',
    
'RPOPLPUSH',
    
'RPUSH',
    
'RPUSHX',
    
'SADD',
    
'SAVE',
    
'SCARD',
    
'SCRIPT DEBUG',
    
'SCRIPT EXISTS',
    
'SCRIPT FLUSH',
    
'SCRIPT KILL',
    
'SCRIPT LOAD',
    
'SDIFF',
    
'SDIFFSTORE',
    
'SELECT',
    
'SET',
    
'SETBIT',
    
'SETEX',
    
'SETNX',
    
'SETRANGE',
    
'SHUTDOWN',
    
'SINTER',
    
'SINTERSTORE',
    
'SISMEMBER',
    
'SLAVEOF',
    
'SLOWLOG',
    
'SMEMBERS',
    
'SMOVE',
    
'SORT',
    
'SPOP',
    
'SRANDMEMBER',
    
'SREM',
    
'STRLEN',
    
'SUBSCRIBE',
    
'SUNION',
    
'SUNIONSTORE',
    
'SWAPDB',
    
'SYNC',
    
'TIME',
    
'TOUCH',
    
'TTL',
    
'TYPE',
    
'UNSUBSCRIBE',
    
'UNLINK',
    
'UNWATCH',
    
'WAIT',
    
'WATCH',
    
'XACK',
    
'XADD',
    
'XCLAIM',
    
'XDEL',
    
'XGROUP',
    
'XINFO',
    
'XLEN',
    
'XPENDING',
    
'XRANGE',
    
'XREAD',
    
'XREADGROUP',
    
'XREVRANGE',
    
'XTRIM',
    
'ZADD',
    
'ZCARD',
    
'ZCOUNT',
    
'ZINCRBY',
    
'ZINTERSTORE',
    
'ZLEXCOUNT',
    
'ZRANGE',
    
'ZRANGEBYLEX',
    
'ZREVRANGEBYLEX',
    
'ZRANGEBYSCORE',
    
'ZRANK',
    
'ZREM',
    
'ZREMRANGEBYLEX',
    
'ZREMRANGEBYRANK',
    
'ZREMRANGEBYSCORE',
    
'ZREVRANGE',
    
'ZREVRANGEBYSCORE',
    
'ZREVRANK',
    
'ZSCORE',
    
'ZUNIONSTORE',
    
'SCAN',
    
'SSCAN',
    
'HSCAN',
    
'ZSCAN',
]
$retries public property (available since version 2.0.7)

The number of times a command execution should be retried when a connection failure occurs. This is used in executeCommand() when a yii\redis\SocketException is thrown. Defaults to 0 meaning no retries on failure.

public integer $retries 0
$retryInterval public property (available since version 2.0.10)

The retry interval in microseconds to wait between retry. This is used in executeCommand() when a yii\redis\SocketException is thrown. Defaults to 0 meaning no wait.

$scheme public property (available since version 2.0.18)

The connection scheme used for connecting to the redis server. Defaults to 'tcp'.

public string $scheme 'tcp'
$socket public property
public resource|false $socket null
$socketClientFlags public property (available since version 2.0.5)

Bitmask field which may be set to any combination of connection flags passed to stream_socket_client(). Currently the select of connection flags is limited to STREAM_CLIENT_CONNECT (default), STREAM_CLIENT_ASYNC_CONNECT and STREAM_CLIENT_PERSISTENT.

Warning: STREAM_CLIENT_PERSISTENT will make PHP reuse connections to the same server. If you are using multiple connection objects to refer to different redis databases on the same $port, redis commands may get executed on the wrong database. STREAM_CLIENT_PERSISTENT is only safe to use if you use only one database.

You may still use persistent connections in this case when disambiguating ports as described in a comment on the PHP manual e.g. on the connection used for session storage, specify the port as:

'port' => '6379/session'

See also https://www.php.net/manual/en/function.stream-socket-client.php.

public integer $socketClientFlags STREAM_CLIENT_CONNECT
$unixSocket public property (available since version 2.0.1)

The unix socket path (e.g. /var/run/redis/redis.sock) to use for connecting to the redis server. This can be used instead of $hostname and $port to connect to the server using a unix socket. If a unix socket path is specified, $hostname and $port will be ignored.

public string $unixSocket null
$useSSL public property (available since version 2.0.12)

Send sockets over SSL protocol. Default state is false.

public boolean $useSSL false
$username public property (available since version 2.0.16)

Username for establishing DB connection. Defaults to null meaning AUTH command will be performed without username. Username was introduced in Redis 6.

public string|null $username null

Method Details

Hide inherited methods

__call() public method

Allows issuing all supported commands via magic methods.

$redis->hmset('test_collection', 'key1', 'val1', 'key2', 'val2')
public mixed __call ( string $name, array $params )
$name string

Name of the missing method to execute

$params array

Method call arguments

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

            
__sleep() public method

Closes the connection when this component is being serialized.

public array __sleep ( )

                public function __sleep()
{
    $this->close();
    return array_keys(get_object_vars($this));
}

            
close() public method

Closes the currently active DB connection.

It does nothing if the connection is already closed.

public void close ( )

                public function close(): void
{
    foreach ($this->_pool as $socket) {
        $connection = $this->connectionString . ', database=' . $this->database;
        \Yii::debug('Closing DB connection: ' . $connection, __METHOD__);
        try {
            $this->executeCommand('QUIT');
        } catch (SocketException $e) {
            // ignore errors when quitting a closed connection
        }
        fclose($socket);
    }
    $this->_pool = [];
}

            
executeCommand() public method

Executes a redis command.

For a list of available commands and their parameters see https://redis.io/commands.

The params array should contain the params separated by white space, e.g. to execute SET mykey somevalue NX call the following:

$redis->executeCommand('SET', ['mykey', 'somevalue', 'NX']);
public array|boolean|null|string executeCommand ( string $name, array $params = [] )
$name string

The name of the command

$params array

List of parameters for the command

return array|boolean|null|string

Dependent on the executed command this method will return different data types:

  • true for commands that return "status reply" with the message 'OK' or 'PONG'.
  • string for commands that return "status reply" that does not have the message OK (since version 2.0.1).
  • string for commands that return "integer reply" as the value is in the range of a signed 64 bit integer.
  • string or null for commands that return "bulk reply".
  • array for commands that return "Multi-bulk replies".

See redis protocol description for details on the mentioned reply types.

throws \yii\db\Exception

for commands that return error reply.

                public function executeCommand($name, $params = [])
{
    $this->open();
    $params = array_merge(explode(' ', $name), $params);
    $command = '*' . count($params) . "\r\n";
    foreach ($params as $arg) {
        $command .= '$' . mb_strlen($arg ?? '', '8bit') . "\r\n" . $arg . "\r\n";
    }
    \Yii::debug("Executing Redis Command: {$name}", __METHOD__);
    if ($this->retries > 0) {
        $tries = $this->retries;
        while ($tries-- > 0) {
            try {
                return $this->sendRawCommand($command, $params);
            } catch (SocketException $e) {
                \Yii::error($e, __METHOD__);
                // backup retries, fail on commands that fail inside here
                $retries = $this->retries;
                $this->retries = 0;
                $this->close();
                if ($this->retryInterval > 0) {
                    usleep($this->retryInterval);
                }
                try {
                    $this->open();
                } catch (SocketException $exception) {
                    // Fail to run initial commands, skip current try
                    \Yii::error($exception, __METHOD__);
                    $this->close();
                } catch (Exception $exception) {
                    $this->close();
                }
                $this->retries = $retries;
            }
        }
    }
    return $this->sendRawCommand($command, $params);
}

            
getConnectionString() public method (available since version 2.0.11)

Return the connection string used to open a socket connection. During a redirect (cluster mode) this will be the target of the redirect.

public string getConnectionString ( )
return string

Socket connection string

                public function getConnectionString()
{
    if ($this->unixSocket) {
        return 'unix://' . $this->unixSocket;
    }
    return $this->scheme . '://' . ($this->redirectConnectionString ?: "$this->hostname:$this->port");
}

            
getDriverName() public method

Returns the name of the DB driver for the current dsn.

public string getDriverName ( )
return string

Name of the DB driver

                public function getDriverName()
{
    return 'redis';
}

            
getIsActive() public method

Returns a value indicating whether the DB connection is established.

public boolean getIsActive ( )
return boolean

Whether the DB connection is established

                public function getIsActive(): bool
{
    return ArrayHelper::getValue($this->_pool, $this->connectionString, false) !== false;
}

            
getLuaScriptBuilder() public method

public yii\redis\LuaScriptBuilder getLuaScriptBuilder ( )

                public function getLuaScriptBuilder()
{
    return new LuaScriptBuilder();
}

            
getSocket() public method

Return the connection resource if a connection to the target has been established before, false otherwise.

public resource|false getSocket ( )

                public function getSocket()
{
    return ArrayHelper::getValue($this->_pool, $this->connectionString, false);
}

            
initConnection() protected method

Initializes the DB connection.

This method is invoked right after the DB connection is established. The default implementation triggers an EVENT_AFTER_OPEN event.

protected mixed initConnection ( )

                protected function initConnection()
{
    $this->trigger(self::EVENT_AFTER_OPEN);
}

            
open() public method

Establishes a DB connection.

It does nothing if a DB connection has already been established.

public void open ( )
throws \yii\db\Exception

if connection fails

                public function open(): void
{
    if ($this->socket !== false) {
        return;
    }
    $connection = $this->connectionString . ', database=' . $this->database;
    \Yii::debug('Opening redis DB connection: ' . $connection, __METHOD__);
    $socket = @stream_socket_client(
        $this->connectionString,
        $errorNumber,
        $errorDescription,
        $this->connectionTimeout ?: ini_get('default_socket_timeout'),
        $this->socketClientFlags,
        stream_context_create($this->contextOptions)
    );
    if ($socket) {
        $this->_pool[ $this->connectionString ] = $socket;
        if ($this->dataTimeout !== null) {
            stream_set_timeout($socket, $timeout = (int) $this->dataTimeout, (int) (($this->dataTimeout - $timeout) * 1000000));
        }
        if ($this->useSSL) {
            stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
        }
        if ($this->password !== null) {
            $this->executeCommand('AUTH', array_filter([$this->username, $this->password]));
        }
        if ($this->database !== null) {
            $this->executeCommand('SELECT', [$this->database]);
        }
        $this->initConnection();
    } else {
        \Yii::error("Failed to open redis DB connection ($connection): $errorNumber - $errorDescription", __CLASS__);
        $message = YII_DEBUG ? "Failed to open redis DB connection ($connection): $errorNumber - $errorDescription" : 'Failed to open DB connection.';
        throw new Exception($message, $errorDescription, $errorNumber);
    }
}

            
sendRawCommand() protected method

Sends RAW command string to the server.

protected array|boolean|null|string sendRawCommand ( string $command, array $params )
$command string

Command string

$params array

List of parameters for the command

return array|boolean|null|string

Dependent on the executed command this method will return different data types:

  • true for commands that return "status reply" with the message 'OK' or 'PONG'.
  • string for commands that return "status reply" that does not have the message OK (since version 2.0.1).
  • string for commands that return "integer reply" as the value is in the range of a signed 64 bit integer.
  • string or null for commands that return "bulk reply".
  • array for commands that return "Multi-bulk replies".

See redis protocol description for details on the mentioned reply types.

throws \yii\db\Exception

for commands that return error reply.

throws yii\redis\SocketException

on connection error.

                protected function sendRawCommand($command, $params)
{
    $written = @fwrite($this->socket, $command);
    if ($written === false) {
        throw new SocketException("Failed to write to socket.\nRedis command was: " . $command);
    }
    if ($written !== ($len = mb_strlen($command, '8bit'))) {
        throw new SocketException("Failed to write to socket. $written of $len bytes written.\nRedis command was: " . $command);
    }
    return $this->parseResponse($params, $command);
}

            

Event Details

Hide inherited properties

EVENT_AFTER_OPEN event of type yii\redis\Event

An event that is triggered after a DB connection is established