Redis Cache Adapter

Redis Cache Adapter

See also

This article explains how to configure the Redis adapter when using the Cache as an independent component in any PHP application. Read the Symfony Cache configuration article if you are using it in a Symfony application.

This adapter stores the values in-memory using one (or more) Redis server instances.

Unlike the APCu adapter, and similarly to the Memcached adapter, it is not limited to the current server’s shared memory; you can store contents independent of your PHP environment. The ability to utilize a cluster of servers to provide redundancy and/or fail-over is also available.

Caution

Requirements: At least one Redis server must be installed and running to use this adapter. Additionally, this adapter requires a compatible extension or library that implements \Redis, \RedisArray, RedisCluster, or \Predis.

This adapter expects a Redis, RedisArray, RedisCluster, or Predis instance to be passed as the first parameter. A namespace and default cache lifetime can optionally be passed as the second and third parameters:

  1. use Symfony\Component\Cache\Adapter\RedisAdapter;
  2. $cache = new RedisAdapter(
  3. // the object that stores a valid connection to your Redis system
  4. \Redis $redisConnection,
  5. // the string prefixed to the keys of the items stored in this cache
  6. $namespace = '',
  7. // the default lifetime (in seconds) for cache items that do not define their
  8. // own lifetime, with a value 0 causing items to be stored indefinitely (i.e.
  9. // until RedisAdapter::clear() is invoked or the server(s) are purged)
  10. $defaultLifetime = 0
  11. );

Configure the Connection

The [createConnection()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Cache/Adapter/RedisAdapter.php "Symfony\Component\Cache\Adapter\RedisAdapter::createConnection()") helper method allows creating and configuring the Redis client class instance using a Data Source Name (DSN):

  1. use Symfony\Component\Cache\Adapter\RedisAdapter;
  2. // pass a single DSN string to register a single server with the client
  3. $client = RedisAdapter::createConnection(
  4. 'redis://localhost'
  5. );

The DSN can specify either an IP/host (and an optional port) or a socket path, as well as a password and a database index. To enable TLS for connections, the scheme redis must be replaced by rediss (the second s means “secure”).

Note

A Data Source Name (DSN) for this adapter must use the following format.

  1. redis[s]://[[email protected]][ip|host|socket[:port]][/db-index]

Below are common examples of valid DSNs showing a combination of available values:

  1. use Symfony\Component\Cache\Adapter\RedisAdapter;
  2. // host "my.server.com" and port "6379"
  3. RedisAdapter::createConnection('redis://my.server.com:6379');
  4. // host "my.server.com" and port "6379" and database index "20"
  5. RedisAdapter::createConnection('redis://my.server.com:6379/20');
  6. // host "localhost", auth "abcdef" and timeout 5 seconds
  7. RedisAdapter::createConnection('redis://[email protected]?timeout=5');
  8. // socket "/var/run/redis.sock" and auth "bad-pass"
  9. RedisAdapter::createConnection('redis://[email protected]/var/run/redis.sock');
  10. // a single DSN can define multiple servers using the following syntax:
  11. // host[hostname-or-IP:port] (where port is optional). Sockets must include a trailing ':'
  12. RedisAdapter::createConnection(
  13. 'redis:?host[localhost]&host[localhost:6379]&host[/var/run/redis.sock:]&auth=my-password&redis_cluster=1'
  14. );

Redis Sentinel, which provides high availability for Redis, is also supported when using the Predis library. Use the redis_sentinel parameter to set the name of your service group:

  1. RedisAdapter::createConnection(
  2. 'redis:?host[redis1:26379]&host[redis2:26379]&host[redis3:26379]&redis_sentinel=mymaster'
  3. );

New in version 4.2: The option to define multiple servers in a single DSN was introduced in Symfony 4.2.

New in version 4.4: Redis Sentinel support was introduced in Symfony 4.4.

Note

See the Symfony\Component\Cache\Traits\RedisTrait for more options you can pass as DSN parameters.

Configure the Options

The [createConnection()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/Cache/Adapter/RedisAdapter.php "Symfony\Component\Cache\Adapter\RedisAdapter::createConnection()") helper method also accepts an array of options as its second argument. The expected format is an associative array of key => value pairs representing option names and their respective values:

  1. use Symfony\Component\Cache\Adapter\RedisAdapter;
  2. $client = RedisAdapter::createConnection(
  3. // provide a string dsn
  4. 'redis://localhost:6379',
  5. // associative array of configuration options
  6. [
  7. 'lazy' => false,
  8. 'persistent' => 0,
  9. 'persistent_id' => null,
  10. 'tcp_keepalive' => 0,
  11. 'timeout' => 30,
  12. 'read_timeout' => 0,
  13. 'retry_interval' => 0,
  14. ]
  15. );

Available Options

class (type: string)

Specifies the connection library to return, either \Redis or \Predis\Client. If none is specified, it will return \Redis if the redis extension is available, and \Predis\Client otherwise.

lazy (type: bool, default: false)

Enables or disables lazy connections to the backend. It’s false by default when using this as a stand-alone component and true by default when using it inside a Symfony application.

persistent (type: int, default: 0)

Enables or disables use of persistent connections. A value of 0 disables persistent connections, and a value of 1 enables them.

persistent_id (type: string|null, default: null)

Specifies the persistent id string to use for a persistent connection.

read_timeout (type: int, default: 0)

Specifies the time (in seconds) used when performing read operations on the underlying network resource before the operation times out.

retry_interval (type: int, default: 0)

Specifies the delay (in milliseconds) between reconnection attempts in case the client loses connection with the server.

tcp_keepalive (type: int, default: 0)

Specifies the TCP-keepalive timeout (in seconds) of the connection. This requires phpredis v4 or higher and a TCP-keepalive enabled server.

timeout (type: int, default: 30)

Specifies the time (in seconds) used to connect to a Redis server before the connection attempt times out.

Note

When using the Predis library some additional Predis-specific options are available. Reference the Predis Connection Parameters documentation for more information.

Working with Tags

In order to use tag-based invalidation, you can wrap your adapter in Symfony\Component\Cache\Adapter\TagAwareAdapter, but when Redis is used as backend, it’s often more interesting to use the dedicated Symfony\Component\Cache\Adapter\RedisTagAwareAdapter. Since tag invalidation logic is implemented in Redis itself, this adapter offers better performance when using tag-based invalidation:

  1. use Symfony\Component\Cache\Adapter\RedisAdapter;
  2. use Symfony\Component\Cache\Adapter\RedisTagAwareAdapter;
  3. $client = RedisAdapter::createConnection('redis://localhost');
  4. $cache = new RedisTagAwareAdapter($client);

Configuring Redis

When using Redis as cache, you should configure the maxmemory and maxmemory-policy settings. By setting maxmemory, you limit how much memory Redis is allowed to consume. If the amount is too low, Redis will drop entries that would still be useful and you benefit less from your cache. Setting the maxmemory-policy to allkeys-lru tells Redis that it is ok to drop data when it runs out of memory, and to first drop the oldest entries (least recently used). If you do not allow Redis to drop entries, it will return an error when you try to add data when no memory is available. An example setting could look as follows:

  1. maxmemory 100mb
  2. maxmemory-policy allkeys-lru

Read more about this topic in the offical Redis LRU Cache Documentation.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.