From d4292b77e3bf73ea20426f6d7bff568d991e5e7c Mon Sep 17 00:00:00 2001 From: Rob Frawley 2nd Date: Wed, 14 Dec 2016 21:49:02 -0500 Subject: [PATCH 1/4] refactor cache pool documentation and add memcached adapter docs --- components/cache/adapters/apcu_adapter.rst | 26 ++ .../cache/adapters/array_cache_adapter.rst | 20 + components/cache/adapters/chain_adapter.rst | 26 ++ .../cache/adapters/doctrine_adapter.rst | 22 ++ .../cache/adapters/filesystem_adapter.rst | 23 ++ .../cache/adapters/memcached_adapter.rst | 365 ++++++++++++++++++ .../adapters/pdo_doctrine_dbal_adapter.rst | 28 ++ .../adapters/php_array_cache_adapter.rst | 38 ++ components/cache/adapters/proxy_adapter.rst | 19 + components/cache/adapters/redis_adapter.rst | 34 ++ components/cache/cache_invalidation.rst | 4 +- components/cache/cache_items.rst | 6 +- components/cache/cache_pools.rst | 303 +-------------- 13 files changed, 619 insertions(+), 295 deletions(-) create mode 100644 components/cache/adapters/apcu_adapter.rst create mode 100644 components/cache/adapters/array_cache_adapter.rst create mode 100644 components/cache/adapters/chain_adapter.rst create mode 100644 components/cache/adapters/doctrine_adapter.rst create mode 100644 components/cache/adapters/filesystem_adapter.rst create mode 100644 components/cache/adapters/memcached_adapter.rst create mode 100644 components/cache/adapters/pdo_doctrine_dbal_adapter.rst create mode 100644 components/cache/adapters/php_array_cache_adapter.rst create mode 100644 components/cache/adapters/proxy_adapter.rst create mode 100644 components/cache/adapters/redis_adapter.rst diff --git a/components/cache/adapters/apcu_adapter.rst b/components/cache/adapters/apcu_adapter.rst new file mode 100644 index 00000000000..be20a75c560 --- /dev/null +++ b/components/cache/adapters/apcu_adapter.rst @@ -0,0 +1,26 @@ +.. index:: + single: Cache Pool + single: APC Cache, APCu Cache + +APCu Cache Adapter +================== + +This adapter can increase the application performance very significantly, +because contents are cached in the shared memory of your server, which is much +faster than the file system. It requires to have installed and enabled the PHP +APCu extension. It's not recommended to use it when performing lots of write and +delete operations because it produces fragmentation in the APCu memory that can +degrade performance significantly:: + + use Symfony\Component\Cache\Adapter\ApcuAdapter; + + $cache = new ApcuAdapter( + // the string prefixed to the keys of the items stored in this cache + $namespace = '', + // in seconds; applied to cache items that don't define their own lifetime + // 0 means to store the cache items indefinitely (i.e. until the APC memory is deleted) + $defaultLifetime = 0, + // if present, this string is added to the namespace to simplify the + // invalidation of the entire cache (e.g. when deploying the application) + $version = null + ); diff --git a/components/cache/adapters/array_cache_adapter.rst b/components/cache/adapters/array_cache_adapter.rst new file mode 100644 index 00000000000..e7fed4ff13f --- /dev/null +++ b/components/cache/adapters/array_cache_adapter.rst @@ -0,0 +1,20 @@ +.. index:: + single: Cache Pool + single: Array Cache + +Array Cache Adapter +=================== + +This adapter is only useful for testing purposes because contents are stored in +memory and not persisted in any way. Besides, some features explained later are +not available, such as the deferred saves:: + + use Symfony\Component\Cache\Adapter\ArrayAdapter; + + $cache = new ArrayAdapter( + // in seconds; applied to cache items that don't define their own lifetime + // 0 means to store the cache items indefinitely (i.e. until the current PHP process finishes) + $defaultLifetime = 0, + // if ``true``, the values saved in the cache are serialized before storing them + $storeSerialized = true + ); diff --git a/components/cache/adapters/chain_adapter.rst b/components/cache/adapters/chain_adapter.rst new file mode 100644 index 00000000000..4f8db162556 --- /dev/null +++ b/components/cache/adapters/chain_adapter.rst @@ -0,0 +1,26 @@ +.. index:: + single: Cache Pool + single: Chain Cache + +Chain Cache Adapter +=================== + +This adapter allows to combine any number of the previous adapters. Cache items +are fetched from the first adapter which contains them. Besides, cache items are +saved in all the given adapters, so this is a simple way of creating a cache +replication:: + + use Symfony\Component\Cache\Adapter\ApcuAdapter; + use Symfony\Component\Cache\Adapter\ChainAdapter; + use Symfony\Component\Cache\Adapter\FilesystemAdapter; + + $apcCache = new ApcuAdapter(); + $fileCache = new FilesystemAdapter(); + + $cache = new ChainAdapter(array($apcCache, $fileCache)); + +When an item is not found in the first adapters but is found in the next ones, +the ``ChainAdapter`` ensures that the fetched item is saved in all the adapters +where it was missing. Since it's not possible to know the expiry date and time +of a cache item, the second optional argument of ``ChainAdapter`` is the default +lifetime applied to those cache items (by default it's ``0``). diff --git a/components/cache/adapters/doctrine_adapter.rst b/components/cache/adapters/doctrine_adapter.rst new file mode 100644 index 00000000000..d5b7a1aa7e9 --- /dev/null +++ b/components/cache/adapters/doctrine_adapter.rst @@ -0,0 +1,22 @@ +.. index:: + single: Cache Pool + single: Doctrine Cache + +Doctrine Cache Adapter +====================== + +This adapter wraps any `Doctrine Cache`_ provider so you can use them in your +application as if they were Symfony Cache adapters:: + + use Doctrine\Common\Cache\SQLite3Cache; + use Symfony\Component\Cache\Adapter\DoctrineAdapter; + + $sqliteDatabase = new \SQLite3(__DIR__.'/cache/data.sqlite'); + $doctrineCache = new SQLite3Cache($sqliteDatabase, 'tableName'); + $symfonyCache = new DoctrineAdapter($doctrineCache); + +This adapter also defines two optional arguments called ``namespace`` (default: +``''``) and ``defaultLifetime`` (default: ``0``) and adapts them to make them +work in the underlying Doctrine cache. + +.. _`Doctrine Cache`: https://github.com/doctrine/cache diff --git a/components/cache/adapters/filesystem_adapter.rst b/components/cache/adapters/filesystem_adapter.rst new file mode 100644 index 00000000000..39f62fbcfe1 --- /dev/null +++ b/components/cache/adapters/filesystem_adapter.rst @@ -0,0 +1,23 @@ +.. index:: + single: Cache Pool + single: Filesystem Cache + +Filesystem Cache Adapter +======================== + +This adapter is useful when you want to improve the application performance but +can't install tools like APCu or Redis in the server. This adapter stores the +contents as regular files in a set of directories on the local file system:: + + use Symfony\Component\Cache\Adapter\FilesystemAdapter; + + $cache = new FilesystemAdapter( + // the subdirectory of the main cache directory where cache items are stored + $namespace = '', + // in seconds; applied to cache items that don't define their own lifetime + // 0 means to store the cache items indefinitely (i.e. until the files are deleted) + $defaultLifetime = 0, + // the main cache directory (the application needs read-write permissions on it) + // if none is specified, a directory is created inside the system temporary directory + $directory = null + ); diff --git a/components/cache/adapters/memcached_adapter.rst b/components/cache/adapters/memcached_adapter.rst new file mode 100644 index 00000000000..3a4e2ad585a --- /dev/null +++ b/components/cache/adapters/memcached_adapter.rst @@ -0,0 +1,365 @@ +.. index:: + single: Cache Pool + single: Memcached Cache + +Memcached Cache Adapter +======================= + +.. versionadded:: 3.3 + + The Memcached adapter was introduced in Symfony 3.3. + + +This adapter stores the values in-memory using one (or more) `Memcached server`_ instances. +Unlike the ACPu adapter, and similarly to the Redis 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:** The `Memcached extension`_ as well as a `Memcached server`_ + must be installed, active, and running to use this adapter. + + +This adapter expects a `Memcached`_ instance to be passed as the first parameter. A namespace +and default cache lifetime can optionally be passed as the second and third parameters:: + + use Symfony\Component\Cache\Adapter\MemcachedAdapter; + + $cache = new MemcachedAdapter( + + // the client object that sets options and adds the server instance(s) + \Memcached $client, + + // a string prefixed to the keys of the items stored in this cache + $namespace = '', + + // the default lifetime (in seconds) for cache items that do not define their + // own lifetime, with a value 0 causing items to be stored indefinitely (i.e. + // until MemcachedAdapter::clear() is invoked or the server(s) are restarted) + $defaultLifetime = 0 + + ); + + +Configure the Connection +------------------------ + +The :method:`Symfony\\Component\\Cache\\Adapter\\MemcachedAdapter::createConnection` +helper method allows creating and configuring a `Memcached`_ class instance using a +`Data Source Name (DSN)`_ or an array of DSNs:: + + use Symfony\Component\Cache\Adapter\MemcachedAdapter; + + // pass a single DSN string to register a single server with the client + $client = MemcachedAdapter::createConnection( + 'memcached://localhost' + ); + + // pass an array of DSN strings to register multiple servers with the client + $client = MemcachedAdapter::createConnection(array( + 'memcached://10.0.0.100', + 'memcached://10.0.0.101', + 'memcached://10.0.0.102', + // etc... + )); + +The DSN can specify either an IP/host (and an optional port) or a socket path, as well as a user +and password (for SASL authentication) and a weight (for multiple server prioritization). + +.. note:: + + A `Data Source Name (DSN)`_ for this adapter must use the following format. + + .. code-block:: text + + memcached://[user:pass@][ip|host|socket[:port]][?weight=int] + + +Below are common examples of valid DSNs showing a combination of available values:: + + use Symfony\Component\Cache\Adapter\MemcachedAdapter; + + $client = MemcachedAdapter::createConnection(array( + + // host "my.server.com" and port "11211" + 'memcached://my.server.com:11211' + + // host "localhost" and SASL use "rmf" and pass "abcdef" + 'memcached://rmf:abcdef@localhost' + + // ip "127.0.0.1" and weight of "50" + 'memcached://127.0.0.1?weight=50' + + // socket "/var/run/memcached.sock" and SASL user "user1" and pass "bad-pass" + 'memcached://user1:bad-pass@/var/run/memcached.sock' + + // socket "/var/run/memcached.sock" and weight of "20" + 'memcached:///var/run/memcached.sock?weight=20' + + )); + + +.. tip:: + + The **weight** option allows for prioritizing the registered servers. For example, you + could set your local Memcached instance to "80" and a remote instance to "20" to ensure + favoritizsm of the local instance. This option is always optional, regardless of the + number of servers registered. + + +.. note:: + + The **username** and **password** is used for SASL authentication; it requires that the + memcached extension was compiled with ``--enable-memcached-sasl``. + + +Configure the Options +--------------------- + +The :method:`Symfony\\Component\\Cache\\Adapter\\MemcachedAdapter::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:: + + use Symfony\Component\Cache\Adapter\MemcachedAdapter; + + $client = MemcachedAdapter::createConnection( + + // provide a string dsn or array of dsns + array(), + + // associative array of configuration options + array( + 'compression' => true, + 'libketama_compatible' => true, + 'serializer' => 'igbinary', + ) + + ); + + +Available Options +~~~~~~~~~~~~~~~~~ + +:strong:`compression`: ``bool`` + Enables or disables payload compression, where item values longer than 100 bytes are compressed + during storage and decompressed during retrieval. + + Valid option values include ``true`` and ``false``, + with a default value of ``true``. + + +:strong:`compression_type:` ``string`` + Specifies the compression method used on value payloads. when the **compression** option is enabled. + + Valid option values include ``fastlz`` and ``zlib``, + with a default value that *varies based on flags used at compilation*. + + +:strong:`serializer:` ``string`` + Specifies the serializer to use for serializing non-scalar values. The ``igbinary`` options requires + the igbinary PHP extension to be enabled, as well as the memcached extension to have been compiled with + support for it. + + Valid option values include ``php`` and ``igbinary``, + with a default value of ``php``. + + +:strong:`distribution:` ``string`` + Specifies the item key distribution method amoung the servers. Consistent hashing delivers + better distribution and allows servers to be added to the cluster with minimal cache losses. + + Valid option values include ``modula``, ``consistent``, and ``virtual_bucket``, + with a default value of ``consistent``. + + +:strong:`hash:` ``string`` + Specifies the hashing algorithm used for item keys. Each hash algorithm has its advantages + and its disadvantages. The default is suggested for comptability with other clients. + + Valid option values include ``default``, ``md5``, ``crc``, ``fnv1_64``, ``fnv1a_64``, + ``fnv1_32``, ``fnv1a_32``, ``hsieh``, and ``murmur``, + with a default value of ``md5``. + + +:strong:`prefix_key:` ``string`` + Specifies a "domain" (or "namespace") prepended to your keys. It cannot be longer than 128 + characters and reduces the maximum key size. + + Valid option values include *any alphanumeric string*, + with a default value of *an empty string*. + + +:strong:`server_failure_limit:` ``int`` + Specifies the failure limit for server connection attempts before marking the server as "dead". + The server will remaining in the server pool unless ``auto_eject_hosts`` is enabled. + + Valid option values include *any positive integer*, + with a default value of ``0``. + + +:strong:`auto_eject_hosts:` ``bool`` + Enables or disables a constant, automatic, re-balancing of the cluster by auto-ejecting hosts + that have exceeded the configured ``server_failure_limit``. + + Valid option values include ``true`` and ``false``, + with a default value of ``false``. + + +:strong:`verify_key:` ``bool`` + Enables or disables testing and verifying of all keys used to ensure they are valid and fit within + the design of the protocol being used. + + Valid option values include ``true`` and ``false``, + with a default value of ``false``. + + +:strong:`randomize_replica_read:` ``bool`` + Enables or disables randomization of the replica reads starting point. Normally the read is done from + primary server and in case of a miss the read is done from "primary+1", then "primary+2", all the way + to "n" replicas. This option sets the replica reads as randomized between all available servers; it + allows distributing read load to multiple servers with the expense of more write traffic. + + Valid option values include ``true`` and ``false``, + with a default value of ``false``. + + +:strong:`number_of_replicas:` ``int`` + Specifies the number of replicas that should be stored for each item (on different servers). This does + not dedicate certain memcached servers to store the replicas in, but instead stores the replicas together + with all of the other objects (on the "n" next servers registered). + + Valid option values include *any positive integer*, + with a default value of ``0``. + + +:strong:`libketama_compatible:` ``bool`` + Enables or disables "libketama" compatible behavior, enabling other libketama-based clients to access + the keys stored by client instance transparently (like Python and Ruby). Enabling this option sets + the ``hash`` option to ``md5`` and the ``distribution`` option to ``consistent``. + + Valid option values include ``true`` and ``false``, + with a default value of ``true``. + + +:strong:`buffer_writes:` ``bool`` + Enables or disables buffered input/output operations, causing storage commands to buffer instead of + being immediately sent to the remote server(s). Any action that retrieves data, quits the connection, + or closes down the connection will cause the buffer to be committed. + + Valid option values include ``true`` and ``false``, + with a default value of ``false``. + + +:strong:`no_block:` ``bool`` + Enables or disables asynchronous input and output operations. This is the fastest transport option + available for storage functions. + + Valid option values include ``true`` and ``false``, + with a default value of ``true``. + + +:strong:`tcp_nodelay:` ``bool`` + Enables or disables the "`no-delay`_" (Nagle's algorithm) `Transmission Control Protocol (TCP)`_ + algorithm, which is a mechanism intended to improve the efficiency of networks by reducing the + overhead of TCP headers by combining a number of small outgoing messages and sending them all at + once. + + Valid option values include ``true`` and ``false``, + with a default value of ``false``. + + +:strong:`tcp_keepalive:` ``bool`` + Enables or disables the "`keep-alive`_" `Transmission Control Protocol (TCP)`_ feature, which is a + feature that helps to determine whether the other end has stopped responding by sending probes to + the network peer after an idle period and closing or persisting the socket based on the response + (or lack thereof). + + Valid option values include ``true`` and ``false``, + with a default value of ``false``. + + +:strong:`use_udp:` ``bool`` + Enables or disabled the use of `User Datagram Protocol (UDP)`_ mode (instead of + `Transmission Control Protocol (TCP)`_ mode), where all operations are executed in a + "fire-and-forget" manner; no attempt to ensure the operation has been received or acted + on will be made once the client has executed it. + + Valid option values include ``true`` and ``false``, + with a default value of ``false``. + + .. caution:: + + **Caution:** + Not all library operations are tested in this mode. Mixed TCP and UDP servers are not allowed. + + +:strong:`socket_send_size:` ``int`` + Specified the maximum buffer size (in bytes) in the context of outgoing (send) socket connection data. + + Valid option values include *any positive integer*, + with a default value that *varies by platform and kernel configuration*. + + +:strong:`socket_recv_size:` ``int`` + Specified the maximum buffer size (in bytes) in the context of incomming (recieve) socket connection data. + + Valid option values include *any positive integer*, + with a default value that *varies by platform and kernel configuration*. + + +:strong:`connect_timeout:` ``int`` + Specifies the timeout (in milliseconds) of socket connection operations when the ``no_block`` option + is enabled. + + Valid option values include *any positive integer*, + with a default value of ``1000``. + + +:strong:`retry_timeout:` ``int`` + Specifies the amount of time (in seconds) before timing out and retrying a connection attempt. + + Valid option values include *any positive integer*, + with a default value of ``0``. + + +:strong:`send_timeout:` ``int`` + Specifies the amount of time (in microseconds) before timing out during an incomming socket (send) operation. + When the ``no_block`` option isn't enabled, this will allow you to still have timeouts on the sending of data. + + Valid option values include ``0`` or *any positive integer*, + with a default value of ``0``. + + +:strong:`recv_timeout:` ``int`` + Specifies he amount of time (in microseconds) before timing out during an outgoing socket (read) operation. + When the ``no_block`` option isn't enabled, this will allow you to still have timeouts on the reading of data. + + Valid option values include ``0`` or *any positive integer*, + with a default value of ``0``. + + +:strong:`poll_timeout:` ``int`` + Specifies the amount of time (in seconds) before + The amount of time (in seconds) before timing out during a socket polling operation. + + Valid option values include *any positive integer*, + with a default value of ``1000``. + + +.. tip:: + Reference the `Memcached extension`_'s `predefined constants`_ documentation for + additional information about the available options. + + +.. _`Transmission Control Protocol (TCP)`: https://en.wikipedia.org/wiki/Transmission_Control_Protocol +.. _`User Datagram Protocol (UDP)`: https://en.wikipedia.org/wiki/User_Datagram_Protocol +.. _`no-delay`: https://en.wikipedia.org/wiki/TCP_NODELAY +.. _`keep-alive`: https://en.wikipedia.org/wiki/Keepalive +.. _`Memcached extension`: http://php.net/manual/en/book.memcached.php +.. _`predefined constants`: http://php.net/manual/en/memcached.constants.php +.. _`Memcached server`: https://memcached.org/ +.. _`Memcached`: http://php.net/manual/en/class.memcached.php +.. _`Data Source Name (DSN)`: https://en.wikipedia.org/wiki/Data_source_name +.. _`Domain Name System (DNS)`: https://en.wikipedia.org/wiki/Domain_Name_System diff --git a/components/cache/adapters/pdo_doctrine_dbal_adapter.rst b/components/cache/adapters/pdo_doctrine_dbal_adapter.rst new file mode 100644 index 00000000000..539419b39bc --- /dev/null +++ b/components/cache/adapters/pdo_doctrine_dbal_adapter.rst @@ -0,0 +1,28 @@ +.. index:: + single: Cache Pool + single: PDO Cache, Doctrine DBAL Cache + +PDO & Doctrine DBAL Cache Adapter +================================= + +.. versionadded:: 3.2 + + The PDO & Doctrine DBAL adapter was introduced in Symfony 3.2. + + +This adapter stores the cached items a SQL database accessed through a PDO or a +Doctrine DBAL connection:: + + use Symfony\Component\Cache\Adapter\PdoAdapter; + + $cache = new PdoAdapter( + // a PDO, a Doctrine DBAL connection or DSN for lazy connecting through PDO + $databaseConnectionOrDSN, + // the string prefixed to the keys of the items stored in this cache + $namespace = '', + // in seconds; applied to cache items that don't define their own lifetime + // 0 means to store the cache items indefinitely (i.e. until the database is cleared) + $defaultLifetime = 0, + // an array of options for configuring the database connection + $options = array() + ); diff --git a/components/cache/adapters/php_array_cache_adapter.rst b/components/cache/adapters/php_array_cache_adapter.rst new file mode 100644 index 00000000000..2a45c3cf759 --- /dev/null +++ b/components/cache/adapters/php_array_cache_adapter.rst @@ -0,0 +1,38 @@ +.. index:: + single: Cache Pool + single: PHP Array Cache + +Php Array Cache Adapter +======================= + +This adapter is a highly performant way to cache static data (e.g. application configuration) +that is optimized and preloaded into OPcache memory storage:: + + use Symfony\Component\Cache\Adapter\PhpArrayAdapter; + use Symfony\Component\Cache\Adapter\PhpFilesAdapter; + + // somehow, decide it's time to warm up the cache! + if ($needsWarmup) { + // some static values + $values = array( + 'stats.num_products' => 4711, + 'stats.num_users' => 1356, + ); + + $cache = new PhpArrayAdapter( + // single file where values are cached + __DIR__ . '/somefile.cache', + // a backup adapter, if you set values after warmup + new FilesystemAdapter() + ); + $cache->warmUp($values); + } + + // ... then, use the cache! + $cacheItem = $cache->getItem('stats.num_users'); + echo $cacheItem->get(); + +.. note:: + + This adapter requires PHP 7.x and should be used with the php.ini setting + ``opcache.enable`` on. diff --git a/components/cache/adapters/proxy_adapter.rst b/components/cache/adapters/proxy_adapter.rst new file mode 100644 index 00000000000..7fe734834ae --- /dev/null +++ b/components/cache/adapters/proxy_adapter.rst @@ -0,0 +1,19 @@ +.. index:: + single: Cache Pool + single: Proxy Cache + +Proxy Cache Adapter +=================== + +This adapter is useful to integrate in your application cache pools not created +with the Symfony Cache component. As long as those cache pools implement the +``CacheItemPoolInterface`` interface, this adapter allows you to get items from +that external cache and save them in the Symfony cache of your application:: + + use Symfony\Component\Cache\Adapter\ProxyAdapter; + + // ... create $nonSymfonyCache somehow + $cache = new ProxyAdapter($nonSymfonyCache); + +The adapter accepts two additional optional arguments: the namespace (``''`` by +default) and the default lifetime (``0`` by default). diff --git a/components/cache/adapters/redis_adapter.rst b/components/cache/adapters/redis_adapter.rst new file mode 100644 index 00000000000..87a7386b6ee --- /dev/null +++ b/components/cache/adapters/redis_adapter.rst @@ -0,0 +1,34 @@ +.. index:: + single: Cache Pool + single: Redis Cache + +Redis Cache Adapter +=================== + +This adapter stores the contents in the memory of a Redis server. Unlike the APCu +adapter, it's not limited to the shared memory of the current server, so you can +store contents in a cluster of servers if needed. + +It requires to have installed Redis and have created a connection that implements +the ``\Redis``, ``\RedisArray``, ``\RedisCluster`` or ``\Predis`` classes:: + + use Symfony\Component\Cache\Adapter\RedisAdapter; + + $cache = new RedisAdapter( + // the object that stores a valid connection to your Redis system + \Redis $redisConnection, + // the string prefixed to the keys of the items stored in this cache + $namespace = '', + // in seconds; applied to cache items that don't define their own lifetime + // 0 means to store the cache items indefinitely (i.e. until the Redis memory is deleted) + $defaultLifetime = 0 + ); + +The :method:`Symfony\\Component\\Cache\\Adapter\\RedisAdapter::createConnection` +helper method allows creating a connection to a Redis server using a `Data Source Name (DSN)`_:: + + $redisConnection = RedisAdapter::createConnection('redis://localhost'); + +See the method's docblock for more options. + +.. _`Data Source Name (DSN)`: https://en.wikipedia.org/wiki/Data_source_name diff --git a/components/cache/cache_invalidation.rst b/components/cache/cache_invalidation.rst index 443700e1bf1..fe661c618ab 100644 --- a/components/cache/cache_invalidation.rst +++ b/components/cache/cache_invalidation.rst @@ -1,6 +1,6 @@ .. index:: - single: Cache; Invalidation - single: Cache; Tags + single: Cache; Invalidation + single: Cache; Tags Cache Invalidation ================== diff --git a/components/cache/cache_items.rst b/components/cache/cache_items.rst index 71c1e9b39da..b534721859e 100644 --- a/components/cache/cache_items.rst +++ b/components/cache/cache_items.rst @@ -1,7 +1,7 @@ .. index:: - single: Cache Item - single: Cache Expiration - single: Cache Exceptions + single: Cache Item + single: Cache Expiration + single: Cache Exceptions Cache Items =========== diff --git a/components/cache/cache_pools.rst b/components/cache/cache_pools.rst index 948a5de5e5d..bb6acad746f 100644 --- a/components/cache/cache_pools.rst +++ b/components/cache/cache_pools.rst @@ -1,9 +1,13 @@ .. index:: - single: Cache Pool - single: APC Cache, APCu Cache - single: Doctrine Cache - single: Redis Cache - single: PDO Cache, Doctrine DBAL Cache + single: Cache Pool + single: APC Cache, APCu Cache + single: Array Cache + single: Chain Cache + single: Doctrine Cache + single: Filesystem Cache + single: Memcached Cache + single: PDO Cache, Doctrine DBAL Cache + single: Redis Cache Cache Pools and Supported Adapters ================================== @@ -21,289 +25,11 @@ Cache Pools are created through the **cache adapters**, which are classes that implement :class:`Symfony\\Component\\Cache\\Adapter\\AdapterInterface`. This component provides several adapters ready to use in your applications. -Array Cache Adapter -~~~~~~~~~~~~~~~~~~~ +.. toctree:: + :glob: + :maxdepth: 1 -This adapter is only useful for testing purposes because contents are stored in -memory and not persisted in any way. Besides, some features explained later are -not available, such as the deferred saves:: - - use Symfony\Component\Cache\Adapter\ArrayAdapter; - - $cache = new ArrayAdapter( - // in seconds; applied to cache items that don't define their own lifetime - // 0 means to store the cache items indefinitely (i.e. until the current PHP process finishes) - $defaultLifetime = 0, - // if ``true``, the values saved in the cache are serialized before storing them - $storeSerialized = true - ); - -Filesystem Cache Adapter -~~~~~~~~~~~~~~~~~~~~~~~~ - -This adapter is useful when you want to improve the application performance but -can't install tools like APCu or Redis in the server. This adapter stores the -contents as regular files in a set of directories on the local file system:: - - use Symfony\Component\Cache\Adapter\FilesystemAdapter; - - $cache = new FilesystemAdapter( - // the subdirectory of the main cache directory where cache items are stored - $namespace = '', - // in seconds; applied to cache items that don't define their own lifetime - // 0 means to store the cache items indefinitely (i.e. until the files are deleted) - $defaultLifetime = 0, - // the main cache directory (the application needs read-write permissions on it) - // if none is specified, a directory is created inside the system temporary directory - $directory = null - ); - -Php Files Cache Adapter -~~~~~~~~~~~~~~~~~~~~~~~ - -This adapter is very similar to the Filesystem adapter, except that the saving creates -a ``.php`` file, which is included on fetch (allowing the file to be saved in OPcache):: - - use Symfony\Component\Cache\Adapter\PhpFilesAdapter; - - $cache = new PhpFilesAdapter( - // the subdirectory of the main cache directory where cache items are stored - $namespace = '', - // in seconds; applied to cache items that don't define their own lifetime - // 0 means to store the cache items indefinitely (i.e. until the files are deleted) - $defaultLifetime = 0, - // the main cache directory (the application needs read-write permissions on it) - // if none is specified, a directory is created inside the system temporary directory - $directory = null - ); - -APCu Cache Adapter -~~~~~~~~~~~~~~~~~~ - -This adapter can increase the application performance very significantly, -because contents are cached in the shared memory of your server, which is much -faster than the file system. It requires to have installed and enabled the PHP -APCu extension. It's not recommended to use it when performing lots of write and -delete operations because it produces fragmentation in the APCu memory that can -degrade performance significantly:: - - use Symfony\Component\Cache\Adapter\ApcuAdapter; - - $cache = new ApcuAdapter( - // the string prefixed to the keys of the items stored in this cache - $namespace = '', - // in seconds; applied to cache items that don't define their own lifetime - // 0 means to store the cache items indefinitely (i.e. until the APC memory is deleted) - $defaultLifetime = 0, - // if present, this string is added to the namespace to simplify the - // invalidation of the entire cache (e.g. when deploying the application) - $version = null - ); - -Redis Cache Adapter -~~~~~~~~~~~~~~~~~~~ - -This adapter stores the contents in the memory of a Redis server. Unlike the APCu -adapter, it's not limited to the shared memory of the current server, so you can -store contents in a cluster of servers if needed. - -Before you start, make sure you have Redis running and have created a connection -that implements the ``\Redis``, ``\RedisArray``, ``\RedisCluster`` or ``\Predis`` -classes:: - - use Symfony\Component\Cache\Adapter\RedisAdapter; - - $cache = new RedisAdapter( - // the object that stores a valid connection to your Redis system - \Redis $redisConnection, - // the string prefixed to the keys of the items stored in this cache - $namespace = '', - // in seconds; applied to cache items that don't define their own lifetime - // 0 means to store the cache items indefinitely (i.e. until the Redis memory is deleted) - $defaultLifetime = 0 - ); - -The :method:`Symfony\\Component\\Cache\\Adapter\\RedisAdapter::createConnection` -helper allows creating a connection to a Redis server using a DSN configuration:: - - $redisConnection = RedisAdapter::createConnection('redis://localhost'); - - $cache = new RedisAdapter($redisConnection); - -See the method's docblock for more options. - -Memcached Cache Adapter -~~~~~~~~~~~~~~~~~~~~~~~ - -This adapter stores the contents into a set of `Memcached`_ servers. - -Before you start, make sure you have Memcached running and have created a -:phpclass:`Memcached` object:: - - use Symfony\Component\Cache\Adapter\MemcachedAdapter; - - $cache = new MemcachedAdapter( - // the object that stores a valid connection to your Memcached servers - \Memcached $client, - // the string prefixed to the keys of the items stored in this cache - $namespace = '', - // in seconds; applied to cache items that don't define their own lifetime - // 0 means to store the cache items indefinitely (i.e. until the Memcached memory is deleted) - $defaultLifetime = 0 - ); - -The :method:`Symfony\\Component\\Cache\\Adapter\\Memcached::createConnection` -helper allows creating a connection to a pool of Memcached server using a DSN configuration:: - - $memcachedClient = MemcachedAdapter::createConnection( - 'memcached://user:pass@localhost?weight=33', - - // options, including username, password and Memcached::OPT_* options - array('persistent_id' => '_products_cache') - ); - - // alternate syntax: array notations for the servers - $memcachedClient = MemcachedAdapter::createConnection(array( - array('192.168.1.100', 11211, 33), - array('192.168.1.101', 11211, 33) - )); - - $cache = new MemcachedAdapter($memcachedClient); - -See the method's docblock for more options. - -PDO & Doctrine DBAL Cache Adapter -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. versionadded:: 3.2 - The PDO & Doctrine DBAL adapter was introduced in Symfony 3.2. - -This adapter stores the cached items a SQL database accessed through a PDO or a -Doctrine DBAL connection:: - - use Symfony\Component\Cache\Adapter\PdoAdapter; - - $cache = new PdoAdapter( - // a PDO, a Doctrine DBAL connection or DSN for lazy connecting through PDO - $databaseConnectionOrDSN, - // the string prefixed to the keys of the items stored in this cache - $namespace = '', - // in seconds; applied to cache items that don't define their own lifetime - // 0 means to store the cache items indefinitely (i.e. until the database is cleared) - $defaultLifetime = 0, - // an array of options for configuring the database connection - $options = array() - ); - -Chain Cache Adapter -~~~~~~~~~~~~~~~~~~~ - -This adapter allows to combine any number of the previous adapters. Cache items -are fetched from the first adapter which contains them. Besides, cache items are -saved in all the given adapters, so this is a simple way of creating a cache -replication:: - - use Symfony\Component\Cache\Adapter\ApcuAdapter; - use Symfony\Component\Cache\Adapter\ChainAdapter; - use Symfony\Component\Cache\Adapter\FilesystemAdapter; - - $apcCache = new ApcuAdapter(); - $fileCache = new FilesystemAdapter(); - - $cache = new ChainAdapter(array($apcCache, $fileCache)); - -When an item is not found in the first adapters but is found in the next ones, -the ``ChainAdapter`` ensures that the fetched item is saved in all the adapters -where it was missing. Since it's not possible to know the expiry date and time -of a cache item, the second optional argument of ``ChainAdapter`` is the default -lifetime applied to those cache items (by default it's ``0``). - -Traceable Adapter -~~~~~~~~~~~~~~~~~ - -This adapter wraps another adapter, and allows you to read a report of all of the -"calls" made to the adapter, including how long actions took, cache hits, misses -and more:: - - use Symfony\Component\Cache\Adapter\TraceableAdapter; - use Symfony\Component\Cache\Adapter\FilesystemAdapter; - - $fileCache = new FilesystemAdapter(); - - $cache = new TraceableAdapter($fileCache); - - // work with the $cache adapter like normal - - // returns an array of TraceableAdapterEvent describing the calls - $events = $cache->getCalls(); - -Proxy Cache Adapter -~~~~~~~~~~~~~~~~~~~ - -This adapter is useful to integrate in your application cache pools not created -with the Symfony Cache component. As long as those cache pools implement the -``CacheItemPoolInterface`` interface, this adapter allows you to get items from -that external cache and save them in the Symfony cache of your application:: - - use Symfony\Component\Cache\Adapter\ProxyAdapter; - - // ... create $nonSymfonyCache somehow - $cache = new ProxyAdapter($nonSymfonyCache); - -The adapter accepts two additional optional arguments: the namespace (``''`` by -default) and the default lifetime (``0`` by default). - -Doctrine Cache Adapter -~~~~~~~~~~~~~~~~~~~~~~ - -This adapter wraps any `Doctrine Cache`_ provider so you can use them in your -application as if they were Symfony Cache adapters:: - - use Doctrine\Common\Cache\SQLite3Cache; - use Symfony\Component\Cache\Adapter\DoctrineAdapter; - - $sqliteDatabase = new \SQLite3(__DIR__.'/cache/data.sqlite'); - $doctrineCache = new SQLite3Cache($sqliteDatabase, 'tableName'); - $symfonyCache = new DoctrineAdapter($doctrineCache); - -This adapter also defines two optional arguments called ``namespace`` (default: -``''``) and ``defaultLifetime`` (default: ``0``) and adapts them to make them -work in the underlying Doctrine cache. - -Php Array Cache Adapter -~~~~~~~~~~~~~~~~~~~~~~~ - -This adapter is a highly performant way to cache static data (e.g. application configuration) -that is optimized and preloaded into OPcache memory storage:: - - use Symfony\Component\Cache\Adapter\PhpArrayAdapter; - use Symfony\Component\Cache\Adapter\PhpFilesAdapter; - - // somehow, decide it's time to warm up the cache! - if ($needsWarmup) { - // some static values - $values = array( - 'stats.num_products' => 4711, - 'stats.num_users' => 1356, - ); - - $cache = new PhpArrayAdapter( - // single file where values are cached - __DIR__ . '/somefile.cache', - // a backup adapter, if you set values after warmup - new FilesystemAdapter() - ); - $cache->warmUp($values); - } - - // ... then, use the cache! - $cacheItem = $cache->getItem('stats.num_users'); - echo $cacheItem->get(); - -.. note:: - - This adapter requires PHP 7.x and should be used with the php.ini setting - ``opcache.enable`` on. + adapters/* Looking for Cache Items ----------------------- @@ -393,6 +119,3 @@ when all items are successfully deleted):: // ... $cacheIsEmpty = $cache->clear(); - -.. _`Doctrine Cache`: https://github.com/doctrine/cache -.. _`Memcached`: http://php.net/manual/en/book.memcached.php From e3eff5b4d394599b976745b09fac28990fa274cd Mon Sep 17 00:00:00 2001 From: Javier Eguiluz Date: Wed, 11 Jan 2017 16:41:53 +0100 Subject: [PATCH 2/4] Reviewed the entire article --- .../cache/adapters/memcached_adapter.rst | 365 +++++++----------- 1 file changed, 145 insertions(+), 220 deletions(-) diff --git a/components/cache/adapters/memcached_adapter.rst b/components/cache/adapters/memcached_adapter.rst index 3a4e2ad585a..10295bb5b77 100644 --- a/components/cache/adapters/memcached_adapter.rst +++ b/components/cache/adapters/memcached_adapter.rst @@ -9,26 +9,24 @@ Memcached Cache Adapter The Memcached adapter was introduced in Symfony 3.3. - -This adapter stores the values in-memory using one (or more) `Memcached server`_ instances. -Unlike the ACPu adapter, and similarly to the Redis 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. +This adapter stores the values in-memory using one (or more) `Memcached server`_ +instances. Unlike the ACPu adapter, and similarly to the Redis 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:** The `Memcached extension`_ as well as a `Memcached server`_ - must be installed, active, and running to use this adapter. - + The `Memcached PHP extension`_ as well as a `Memcached server`_ must be + installed, active, and running to use this adapter. -This adapter expects a `Memcached`_ instance to be passed as the first parameter. A namespace -and default cache lifetime can optionally be passed as the second and third parameters:: +This adapter expects a `Memcached`_ instance to be passed as the first +parameter. A namespace and default cache lifetime can optionally be passed as +the second and third parameters:: use Symfony\Component\Cache\Adapter\MemcachedAdapter; $cache = new MemcachedAdapter( - // the client object that sets options and adds the server instance(s) \Memcached $client, @@ -39,10 +37,8 @@ and default cache lifetime can optionally be passed as the second and third para // own lifetime, with a value 0 causing items to be stored indefinitely (i.e. // until MemcachedAdapter::clear() is invoked or the server(s) are restarted) $defaultLifetime = 0 - ); - Configure the Connection ------------------------ @@ -65,68 +61,52 @@ helper method allows creating and configuring a `Memcached`_ class instance usin // etc... )); -The DSN can specify either an IP/host (and an optional port) or a socket path, as well as a user -and password (for SASL authentication) and a weight (for multiple server prioritization). - -.. note:: +The `Data Source Name (DSN)`_ for this adapter must use the following format: - A `Data Source Name (DSN)`_ for this adapter must use the following format. +.. code-block:: text - .. code-block:: text - - memcached://[user:pass@][ip|host|socket[:port]][?weight=int] + memcached://[user:pass@][ip|host|socket[:port]][?weight=int] +The DSN must include a IP/host (and an optional port) or a socket path, an +optional username and password (for SASL authentication; it requires that the +memcached extension was compiled with ``--enable-memcached-sasl``) and an +optional weight (for prioritizing servers in a cluster; its value is an integer +between ``0`` and ``100`` which defaults to ``XX``; a higher value means more +priority). Below are common examples of valid DSNs showing a combination of available values:: use Symfony\Component\Cache\Adapter\MemcachedAdapter; $client = MemcachedAdapter::createConnection(array( - - // host "my.server.com" and port "11211" + // hostname + port 'memcached://my.server.com:11211' - // host "localhost" and SASL use "rmf" and pass "abcdef" + // hostname without port + SASL username and password 'memcached://rmf:abcdef@localhost' - // ip "127.0.0.1" and weight of "50" + // IP address instead of hostname + weight 'memcached://127.0.0.1?weight=50' - // socket "/var/run/memcached.sock" and SASL user "user1" and pass "bad-pass" - 'memcached://user1:bad-pass@/var/run/memcached.sock' + // socket instead of hostname/IP + SASL username and password + 'memcached://janesmith:mypassword@/var/run/memcached.sock' - // socket "/var/run/memcached.sock" and weight of "20" + // socket instead of hostname/IP + weight 'memcached:///var/run/memcached.sock?weight=20' - )); - -.. tip:: - - The **weight** option allows for prioritizing the registered servers. For example, you - could set your local Memcached instance to "80" and a remote instance to "20" to ensure - favoritizsm of the local instance. This option is always optional, regardless of the - number of servers registered. - - -.. note:: - - The **username** and **password** is used for SASL authentication; it requires that the - memcached extension was compiled with ``--enable-memcached-sasl``. - - Configure the Options --------------------- -The :method:`Symfony\\Component\\Cache\\Adapter\\MemcachedAdapter::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:: +The :method:`Symfony\\Component\\Cache\\Adapter\\MemcachedAdapter::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:: use Symfony\Component\Cache\Adapter\MemcachedAdapter; $client = MemcachedAdapter::createConnection( - - // provide a string dsn or array of dsns + // a DSN string or an array of DSN strings array(), // associative array of configuration options @@ -135,229 +115,174 @@ array of ``key => value`` pairs representing option names and their respective v 'libketama_compatible' => true, 'serializer' => 'igbinary', ) - ); - Available Options ~~~~~~~~~~~~~~~~~ -:strong:`compression`: ``bool`` - Enables or disables payload compression, where item values longer than 100 bytes are compressed - during storage and decompressed during retrieval. - - Valid option values include ``true`` and ``false``, - with a default value of ``true``. - +``auto_eject_hosts`` (type: ``bool``, default: ``false``) + Enables or disables a constant, automatic, re-balancing of the cluster by + auto-ejecting hosts that have exceeded the configured ``server_failure_limit``. -:strong:`compression_type:` ``string`` - Specifies the compression method used on value payloads. when the **compression** option is enabled. +``buffer_writes`` (type: ``bool``, default: ``false``) + Enables or disables buffered input/output operations, causing storage + commands to buffer instead of being immediately sent to the remote + server(s). Any action that retrieves data, quits the connection, or closes + down the connection will cause the buffer to be committed. - Valid option values include ``fastlz`` and ``zlib``, - with a default value that *varies based on flags used at compilation*. +``compression`` (type: ``bool``, default: ``true``) + Enables or disables payload compression, where item values longer than 100 + bytes are compressed during storage and decompressed during retrieval. +``compression_type`` (type: ``string``) + Specifies the compression method used on value payloads. when the + **compression** option is enabled. -:strong:`serializer:` ``string`` - Specifies the serializer to use for serializing non-scalar values. The ``igbinary`` options requires - the igbinary PHP extension to be enabled, as well as the memcached extension to have been compiled with - support for it. + Valid option values include ``fastlz`` and ``zlib``, with a default value + that *varies based on flags used at compilation*. - Valid option values include ``php`` and ``igbinary``, - with a default value of ``php``. +``connect_timeout`` (type: ``int``, default: ``1000``) + Specifies the timeout (in milliseconds) of socket connection operations when + the ``no_block`` option is enabled. + Valid option values include *any positive integer*. -:strong:`distribution:` ``string`` - Specifies the item key distribution method amoung the servers. Consistent hashing delivers - better distribution and allows servers to be added to the cluster with minimal cache losses. +``distribution`` (type: ``string``, default: ``consistent``) + Specifies the item key distribution method among the servers. Consistent + hashing delivers better distribution and allows servers to be added to the + cluster with minimal cache losses. - Valid option values include ``modula``, ``consistent``, and ``virtual_bucket``, - with a default value of ``consistent``. + Valid option values include ``modula``, ``consistent``, and ``virtual_bucket``. +``hash`` (type: ``string``, default: ``md5``) + Specifies the hashing algorithm used for item keys. Each hash algorithm has + its advantages and its disadvantages. The default is suggested for compatibility + with other clients. -:strong:`hash:` ``string`` - Specifies the hashing algorithm used for item keys. Each hash algorithm has its advantages - and its disadvantages. The default is suggested for comptability with other clients. + Valid option values include ``default``, ``md5``, ``crc``, ``fnv1_64``, + ``fnv1a_64``, ``fnv1_32``, ``fnv1a_32``, ``hsieh``, and ``murmur``. - Valid option values include ``default``, ``md5``, ``crc``, ``fnv1_64``, ``fnv1a_64``, - ``fnv1_32``, ``fnv1a_32``, ``hsieh``, and ``murmur``, - with a default value of ``md5``. +``libketama_compatible`` (type: ``bool``, default: ``true``) + Enables or disables "libketama" compatible behavior, enabling other + libketama-based clients to access the keys stored by client instance + transparently (like Python and Ruby). Enabling this option sets the ``hash`` + option to ``md5`` and the ``distribution`` option to ``consistent``. +``no_block`` (type: ``bool``, default: ``true``) + Enables or disables asynchronous input and output operations. This is the + fastest transport option available for storage functions. -:strong:`prefix_key:` ``string`` - Specifies a "domain" (or "namespace") prepended to your keys. It cannot be longer than 128 - characters and reduces the maximum key size. +``number_of_replicas`` (type: ``int``, default: ``0``) + Specifies the number of replicas that should be stored for each item (on + different servers). This does not dedicate certain memcached servers to + store the replicas in, but instead stores the replicas together with all of + the other objects (on the "n" next servers registered). - Valid option values include *any alphanumeric string*, - with a default value of *an empty string*. + Valid option values include *any positive integer*. +``prefix_key`` (type: ``string``, default: an empty string) + Specifies a "domain" (or "namespace") prepended to your keys. It cannot be + longer than 128 characters and reduces the maximum key size. -:strong:`server_failure_limit:` ``int`` - Specifies the failure limit for server connection attempts before marking the server as "dead". - The server will remaining in the server pool unless ``auto_eject_hosts`` is enabled. + Valid option values include *any alphanumeric string*. - Valid option values include *any positive integer*, - with a default value of ``0``. +``poll_timeout`` (type: ``int``, default: ``1000``) + Specifies the amount of time (in seconds) before timing out during a socket + polling operation. + Valid option values include *any positive integer*. -:strong:`auto_eject_hosts:` ``bool`` - Enables or disables a constant, automatic, re-balancing of the cluster by auto-ejecting hosts - that have exceeded the configured ``server_failure_limit``. +``randomize_replica_read`` (type: ``bool``, type: ``false``) + Enables or disables randomization of the replica reads starting point. + Normally the read is done from primary server and in case of a miss the read + is done from "primary+1", then "primary+2", all the way to "n" replicas. + This option sets the replica reads as randomized between all available + servers; it allows distributing read load to multiple servers with the + expense of more write traffic. - Valid option values include ``true`` and ``false``, - with a default value of ``false``. - - -:strong:`verify_key:` ``bool`` - Enables or disables testing and verifying of all keys used to ensure they are valid and fit within - the design of the protocol being used. - - Valid option values include ``true`` and ``false``, - with a default value of ``false``. - - -:strong:`randomize_replica_read:` ``bool`` - Enables or disables randomization of the replica reads starting point. Normally the read is done from - primary server and in case of a miss the read is done from "primary+1", then "primary+2", all the way - to "n" replicas. This option sets the replica reads as randomized between all available servers; it - allows distributing read load to multiple servers with the expense of more write traffic. +``recv_timeout`` (type: ``int``, default: ``0``) + Specifies he amount of time (in microseconds) before timing out during an outgoing socket (read) operation. + When the ``no_block`` option isn't enabled, this will allow you to still have timeouts on the reading of data. - Valid option values include ``true`` and ``false``, - with a default value of ``false``. + Valid option values include ``0`` or *any positive integer*. +``retry_timeout`` (type: ``int``, default: ``0``) + Specifies the amount of time (in seconds) before timing out and retrying a + connection attempt. -:strong:`number_of_replicas:` ``int`` - Specifies the number of replicas that should be stored for each item (on different servers). This does - not dedicate certain memcached servers to store the replicas in, but instead stores the replicas together - with all of the other objects (on the "n" next servers registered). + Valid option values include *any positive integer*. - Valid option values include *any positive integer*, - with a default value of ``0``. +``send_timeout`` (type: ``int``, default: ``0``) + Specifies the amount of time (in microseconds) before timing out during an + incoming socket (send) operation. When the ``no_block`` option isn't enabled, + this will allow you to still have timeouts on the sending of data. + Valid option values include ``0`` or *any positive integer*. -:strong:`libketama_compatible:` ``bool`` - Enables or disables "libketama" compatible behavior, enabling other libketama-based clients to access - the keys stored by client instance transparently (like Python and Ruby). Enabling this option sets - the ``hash`` option to ``md5`` and the ``distribution`` option to ``consistent``. +``serializer`` (type: ``string``, default: ``php``) + Specifies the serializer to use for serializing non-scalar values. The + ``igbinary`` options requires the igbinary PHP extension to be enabled, as + well as the memcached extension to have been compiled with support for it. - Valid option values include ``true`` and ``false``, - with a default value of ``true``. + Valid option values include ``php`` and ``igbinary``. +``server_failure_limit`` (type: ``int``, default: ``0``) + Specifies the failure limit for server connection attempts before marking + the server as "dead". The server will remaining in the server pool unless + ``auto_eject_hosts`` is enabled. -:strong:`buffer_writes:` ``bool`` - Enables or disables buffered input/output operations, causing storage commands to buffer instead of - being immediately sent to the remote server(s). Any action that retrieves data, quits the connection, - or closes down the connection will cause the buffer to be committed. + Valid option values include *any positive integer*. - Valid option values include ``true`` and ``false``, - with a default value of ``false``. +``socket_recv_size`` (type: ``int``) + Specified the maximum buffer size (in bytes) in the context of incoming + (receive) socket connection data. + Valid option values include *any positive integer*, with a default value + that *varies by platform and kernel configuration*. -:strong:`no_block:` ``bool`` - Enables or disables asynchronous input and output operations. This is the fastest transport option - available for storage functions. +``socket_send_size`` (type: ``int``) + Specified the maximum buffer size (in bytes) in the context of outgoing (send) + socket connection data. - Valid option values include ``true`` and ``false``, - with a default value of ``true``. + Valid option values include *any positive integer*, with a default value + that *varies by platform and kernel configuration*. +``tcp_keepalive`` (type: ``bool``, default: ``false``) + Enables or disables the "`keep-alive`_" `Transmission Control Protocol (TCP)`_ + feature, which is a feature that helps to determine whether the other end + has stopped responding by sending probes to the network peer after an idle + period and closing or persisting the socket based on the response (or lack thereof). -:strong:`tcp_nodelay:` ``bool`` +``tcp_nodelay`` (type: ``bool``, default: ``false``) Enables or disables the "`no-delay`_" (Nagle's algorithm) `Transmission Control Protocol (TCP)`_ - algorithm, which is a mechanism intended to improve the efficiency of networks by reducing the - overhead of TCP headers by combining a number of small outgoing messages and sending them all at - once. + algorithm, which is a mechanism intended to improve the efficiency of + networks by reducing the overhead of TCP headers by combining a number of + small outgoing messages and sending them all at once. - Valid option values include ``true`` and ``false``, - with a default value of ``false``. - - -:strong:`tcp_keepalive:` ``bool`` - Enables or disables the "`keep-alive`_" `Transmission Control Protocol (TCP)`_ feature, which is a - feature that helps to determine whether the other end has stopped responding by sending probes to - the network peer after an idle period and closing or persisting the socket based on the response - (or lack thereof). - - Valid option values include ``true`` and ``false``, - with a default value of ``false``. - - -:strong:`use_udp:` ``bool`` - Enables or disabled the use of `User Datagram Protocol (UDP)`_ mode (instead of - `Transmission Control Protocol (TCP)`_ mode), where all operations are executed in a - "fire-and-forget" manner; no attempt to ensure the operation has been received or acted - on will be made once the client has executed it. - - Valid option values include ``true`` and ``false``, - with a default value of ``false``. +``use_udp`` (type: ``bool``, default: ``false``) + Enables or disabled the use of `User Datagram Protocol (UDP)`_ mode (instead + of `Transmission Control Protocol (TCP)`_ mode), where all operations are + executed in a "fire-and-forget" manner; no attempt to ensure the operation + has been received or acted on will be made once the client has executed it. .. caution:: - **Caution:** - Not all library operations are tested in this mode. Mixed TCP and UDP servers are not allowed. - - -:strong:`socket_send_size:` ``int`` - Specified the maximum buffer size (in bytes) in the context of outgoing (send) socket connection data. - - Valid option values include *any positive integer*, - with a default value that *varies by platform and kernel configuration*. - - -:strong:`socket_recv_size:` ``int`` - Specified the maximum buffer size (in bytes) in the context of incomming (recieve) socket connection data. - - Valid option values include *any positive integer*, - with a default value that *varies by platform and kernel configuration*. - - -:strong:`connect_timeout:` ``int`` - Specifies the timeout (in milliseconds) of socket connection operations when the ``no_block`` option - is enabled. - - Valid option values include *any positive integer*, - with a default value of ``1000``. - - -:strong:`retry_timeout:` ``int`` - Specifies the amount of time (in seconds) before timing out and retrying a connection attempt. - - Valid option values include *any positive integer*, - with a default value of ``0``. - - -:strong:`send_timeout:` ``int`` - Specifies the amount of time (in microseconds) before timing out during an incomming socket (send) operation. - When the ``no_block`` option isn't enabled, this will allow you to still have timeouts on the sending of data. - - Valid option values include ``0`` or *any positive integer*, - with a default value of ``0``. - - -:strong:`recv_timeout:` ``int`` - Specifies he amount of time (in microseconds) before timing out during an outgoing socket (read) operation. - When the ``no_block`` option isn't enabled, this will allow you to still have timeouts on the reading of data. - - Valid option values include ``0`` or *any positive integer*, - with a default value of ``0``. - - -:strong:`poll_timeout:` ``int`` - Specifies the amount of time (in seconds) before - The amount of time (in seconds) before timing out during a socket polling operation. - - Valid option values include *any positive integer*, - with a default value of ``1000``. + Not all library operations are tested in this mode. Mixed TCP and UDP + servers are not allowed. +``verify_key`` (type: ``bool``, default: ``false``) + Enables or disables testing and verifying of all keys used to ensure they + are valid and fit within the design of the protocol being used. .. tip:: - Reference the `Memcached extension`_'s `predefined constants`_ documentation for - additional information about the available options. - + Reference the `Memcached extension`_'s `predefined constants`_ documentation + for additional information about the available options. .. _`Transmission Control Protocol (TCP)`: https://en.wikipedia.org/wiki/Transmission_Control_Protocol .. _`User Datagram Protocol (UDP)`: https://en.wikipedia.org/wiki/User_Datagram_Protocol .. _`no-delay`: https://en.wikipedia.org/wiki/TCP_NODELAY .. _`keep-alive`: https://en.wikipedia.org/wiki/Keepalive -.. _`Memcached extension`: http://php.net/manual/en/book.memcached.php +.. _`Memcached PHP extension`: http://php.net/manual/en/book.memcached.php .. _`predefined constants`: http://php.net/manual/en/memcached.constants.php .. _`Memcached server`: https://memcached.org/ .. _`Memcached`: http://php.net/manual/en/class.memcached.php From c49d42713a2ce8802b5fcd315aa981259d7c7964 Mon Sep 17 00:00:00 2001 From: Rob Frawley 2nd Date: Thu, 19 Jan 2017 11:15:26 -0500 Subject: [PATCH 3/4] cleanup all cache adapter documentation, extend redis docs --- components/cache.rst | 2 + components/cache/adapters/apcu_adapter.rst | 50 +++++-- .../cache/adapters/array_cache_adapter.rst | 17 ++- components/cache/adapters/chain_adapter.rst | 45 ++++-- .../cache/adapters/doctrine_adapter.rst | 31 +++-- .../cache/adapters/filesystem_adapter.rst | 25 +++- .../cache/adapters/memcached_adapter.rst | 22 +-- .../adapters/pdo_doctrine_dbal_adapter.rst | 26 +++- components/cache/adapters/proxy_adapter.rst | 33 +++-- components/cache/adapters/redis_adapter.rst | 131 ++++++++++++++++-- 10 files changed, 308 insertions(+), 74 deletions(-) diff --git a/components/cache.rst b/components/cache.rst index 2bb5e60bd8b..8f1394e37d6 100644 --- a/components/cache.rst +++ b/components/cache.rst @@ -3,6 +3,8 @@ single: Performance single: Components; Cache +.. _`cache-component`: + The Cache Component =================== diff --git a/components/cache/adapters/apcu_adapter.rst b/components/cache/adapters/apcu_adapter.rst index be20a75c560..e4b052b231b 100644 --- a/components/cache/adapters/apcu_adapter.rst +++ b/components/cache/adapters/apcu_adapter.rst @@ -2,25 +2,53 @@ single: Cache Pool single: APC Cache, APCu Cache +.. _apcu-adapter: + APCu Cache Adapter ================== -This adapter can increase the application performance very significantly, -because contents are cached in the shared memory of your server, which is much -faster than the file system. It requires to have installed and enabled the PHP -APCu extension. It's not recommended to use it when performing lots of write and -delete operations because it produces fragmentation in the APCu memory that can -degrade performance significantly:: +This adapter is a high-performance, shared memory cache. It can increase the +application performance very significantly because the cache contents are +stored in the shared memory of your server, a component that is much faster than +others, such as the file system. + +.. caution:: + + **Requirement:** The `APCu extension`_ must be installed and active to use + this adapter. + +This adapter can be provided an optional namespace string as its first parameter, a +default cache lifetime as its second parameter, and a version string as its third +parameter:: use Symfony\Component\Cache\Adapter\ApcuAdapter; $cache = new ApcuAdapter( - // the string prefixed to the keys of the items stored in this cache + + // a string prefixed to the keys of the items stored in this cache $namespace = '', - // in seconds; applied to cache items that don't define their own lifetime - // 0 means to store the cache items indefinitely (i.e. until the APC memory is deleted) + + // the default lifetime (in seconds) for cache items that do not define their + // own lifetime, with a value 0 causing items to be stored indefinitely (i.e. + // until the APCu memory is cleared) $defaultLifetime = 0, - // if present, this string is added to the namespace to simplify the - // invalidation of the entire cache (e.g. when deploying the application) + + // when set, all keys prefixed by $namespace can be invalidated by changing + // this $version string $version = null ); + +.. caution:: + + It is *not* recommended to use this adapter when performing a large number of + write and delete operations, as these operations result in fragmentation of the + APCu memory, resulting in *significantly* degraded performance. + +.. tip:: + + Note that this adapters CRUD operations are specific to the PHP SAPI it is running + under. This means adding a cache item using the CLI will not result in the item + appearing under FPM. Likewise, deletion of an item using CGI will not result in the + item being deleted under the CLI. + +.. _`APCu extension`: https://pecl.php.net/package/APCu \ No newline at end of file diff --git a/components/cache/adapters/array_cache_adapter.rst b/components/cache/adapters/array_cache_adapter.rst index e7fed4ff13f..ffdc1d60dd0 100644 --- a/components/cache/adapters/array_cache_adapter.rst +++ b/components/cache/adapters/array_cache_adapter.rst @@ -5,16 +5,23 @@ Array Cache Adapter =================== -This adapter is only useful for testing purposes because contents are stored in -memory and not persisted in any way. Besides, some features explained later are -not available, such as the deferred saves:: +Generally, this adapter is useful for testing purposes, as its contents are stored in memory +and not persisted outside the running PHP process in any way. It can also be useful while +warming up caches, due to the :method:`Symfony\\Component\\Cache\\Adapter\\ArrayAdapter::getValues` +method. + +This adapter can be passed a default cache lifetime as its first parameter, and a boolean that +toggles serialization as its second parameter:: use Symfony\Component\Cache\Adapter\ArrayAdapter; $cache = new ArrayAdapter( - // in seconds; applied to cache items that don't define their own lifetime - // 0 means to store the cache items indefinitely (i.e. until the current PHP process finishes) + + // the default lifetime (in seconds) for cache items that do not define their + // own lifetime, with a value 0 causing items to be stored indefinitely (i.e. + // until the current PHP process finishes) $defaultLifetime = 0, + // if ``true``, the values saved in the cache are serialized before storing them $storeSerialized = true ); diff --git a/components/cache/adapters/chain_adapter.rst b/components/cache/adapters/chain_adapter.rst index 4f8db162556..b74bd2048a2 100644 --- a/components/cache/adapters/chain_adapter.rst +++ b/components/cache/adapters/chain_adapter.rst @@ -5,22 +5,39 @@ Chain Cache Adapter =================== -This adapter allows to combine any number of the previous adapters. Cache items -are fetched from the first adapter which contains them. Besides, cache items are -saved in all the given adapters, so this is a simple way of creating a cache -replication:: +This adapter allows to combine any number of the other available cache adapters. +Cache items are fetched from the first adapter which contains them and cache items are +saved in all the given adapters. This offers a simple way of creating a layered cache. + +This adapter expects an array of adapters as its first parameter, and optionally a +maximum cache lifetime as its second parameter:: use Symfony\Component\Cache\Adapter\ApcuAdapter; - use Symfony\Component\Cache\Adapter\ChainAdapter; - use Symfony\Component\Cache\Adapter\FilesystemAdapter; - $apcCache = new ApcuAdapter(); - $fileCache = new FilesystemAdapter(); + $cache = new ChainAdapter(array( + + // The ordered list of adapters used to fetch cached items + array $adapters, + + // The max lifetime of items propagated from lower adapters to upper ones + $maxLifetime = 0 + )); + +.. note:: - $cache = new ChainAdapter(array($apcCache, $fileCache)); + When an item is not found in the first adapters but is found in the next ones, this + adapter ensures that the fetched item is saved in all the adapters where it was + previously missing. + +The following shows how to create a chain adapter instance using the fastest and slowest +storage engines, :class:`Symfony\\Component\\Cache\\Adapter\\ApcuAdapter` and +:class:`Symfony\\Component\\Cache\\Adapter\\FilesystemAdapter`, respectfully:: + + use Symfony\Component\Cache\Adapter\ApcuAdapter; + use Symfony\Component\Cache\Adapter\ChainAdapter; + use Symfony\Component\Cache\Adapter\FilesystemAdapter; -When an item is not found in the first adapters but is found in the next ones, -the ``ChainAdapter`` ensures that the fetched item is saved in all the adapters -where it was missing. Since it's not possible to know the expiry date and time -of a cache item, the second optional argument of ``ChainAdapter`` is the default -lifetime applied to those cache items (by default it's ``0``). + $cache = new ChainAdapter(array( + new ApcuAdapter(), + new FilesystemAdapter(), + )); diff --git a/components/cache/adapters/doctrine_adapter.rst b/components/cache/adapters/doctrine_adapter.rst index d5b7a1aa7e9..5ceefa950de 100644 --- a/components/cache/adapters/doctrine_adapter.rst +++ b/components/cache/adapters/doctrine_adapter.rst @@ -2,21 +2,36 @@ single: Cache Pool single: Doctrine Cache +.. _`doctrine-adapter`: + Doctrine Cache Adapter ====================== -This adapter wraps any `Doctrine Cache`_ provider so you can use them in your -application as if they were Symfony Cache adapters:: +This adapter wraps any class extending the `Doctrine Cache`_ abstract provider, allowing +you to use these providers in your application as if they were Symfony Cache adapters. + +This adapter expects a ``\Doctrine\Common\Cache\CacheProvider`` instance as its first +parameter, and optionally a namespace and default cache lifetime as its second and +third parameters:: + use Doctrine\Common\Cache\CacheProvider; use Doctrine\Common\Cache\SQLite3Cache; use Symfony\Component\Cache\Adapter\DoctrineAdapter; - $sqliteDatabase = new \SQLite3(__DIR__.'/cache/data.sqlite'); - $doctrineCache = new SQLite3Cache($sqliteDatabase, 'tableName'); - $symfonyCache = new DoctrineAdapter($doctrineCache); + $provider = new SQLite3Cache(new \SQLite3(__DIR__.'/cache/data.sqlite'), 'youTableName'); + + $symfonyCache = new DoctrineAdapter( + + // a cache provider instance + CacheProvider $provider, + + // a string prefixed to the keys of the items stored in this cache + $namespace = '', -This adapter also defines two optional arguments called ``namespace`` (default: -``''``) and ``defaultLifetime`` (default: ``0``) and adapts them to make them -work in the underlying Doctrine cache. + // the default lifetime (in seconds) for cache items that do not define their + // own lifetime, with a value 0 causing items to be stored indefinitely (i.e. + // until the database table is truncated or its rows are otherwise deleted) + $defaultLifetime = 0 + ); .. _`Doctrine Cache`: https://github.com/doctrine/cache diff --git a/components/cache/adapters/filesystem_adapter.rst b/components/cache/adapters/filesystem_adapter.rst index 39f62fbcfe1..5c8177199aa 100644 --- a/components/cache/adapters/filesystem_adapter.rst +++ b/components/cache/adapters/filesystem_adapter.rst @@ -6,18 +6,33 @@ Filesystem Cache Adapter ======================== This adapter is useful when you want to improve the application performance but -can't install tools like APCu or Redis in the server. This adapter stores the -contents as regular files in a set of directories on the local file system:: +can't install tools like APCu or Redis on the server. This adapter stores the +contents as regular files in a set of directories on the local file system. + +This adapter can optionally be provided a namespace, default cache lifetime, and +directory path, as its first, second, and third parameters:: use Symfony\Component\Cache\Adapter\FilesystemAdapter; $cache = new FilesystemAdapter( - // the subdirectory of the main cache directory where cache items are stored + + // a string used as the subdirectory of the root cache directory, where cache + // items will be stored $namespace = '', - // in seconds; applied to cache items that don't define their own lifetime - // 0 means to store the cache items indefinitely (i.e. until the files are deleted) + + // the default lifetime (in seconds) for cache items that do not define their + // own lifetime, with a value 0 causing items to be stored indefinitely (i.e. + // until the files are deleted) $defaultLifetime = 0, + // the main cache directory (the application needs read-write permissions on it) // if none is specified, a directory is created inside the system temporary directory $directory = null ); + +.. tip:: + + This adapter is generally the *slowest* due to the overhead of file IO. If throughput is paramount, + the in-memory adapters (such as :ref:`APCu `, :ref:`Memcached `, + and :ref:`Redis `) or the database adapters (such as + :ref:`Doctrine ` and :ref:`PDO & Doctrine `) are recommended. diff --git a/components/cache/adapters/memcached_adapter.rst b/components/cache/adapters/memcached_adapter.rst index 10295bb5b77..413db7d89fa 100644 --- a/components/cache/adapters/memcached_adapter.rst +++ b/components/cache/adapters/memcached_adapter.rst @@ -2,6 +2,8 @@ single: Cache Pool single: Memcached Cache +.. _memcached-adapter: + Memcached Cache Adapter ======================= @@ -10,15 +12,17 @@ Memcached Cache Adapter The Memcached adapter was introduced in Symfony 3.3. This adapter stores the values in-memory using one (or more) `Memcached server`_ -instances. Unlike the ACPu adapter, and similarly to the Redis 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. +instances. Unlike the :ref:`APCu adapter `, and similarly to the +:ref:`Redis 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:: - The `Memcached PHP extension`_ as well as a `Memcached server`_ must be - installed, active, and running to use this adapter. + **Requirements:** The `Memcached PHP extension`_ as well as a `Memcached server`_ + must be installed, active, and running to use this adapter. Version ``2.2`` or + greater of the `Memcached PHP extension`_ is required for this adapter. This adapter expects a `Memcached`_ instance to be passed as the first parameter. A namespace and default cache lifetime can optionally be passed as @@ -71,7 +75,7 @@ The DSN must include a IP/host (and an optional port) or a socket path, an optional username and password (for SASL authentication; it requires that the memcached extension was compiled with ``--enable-memcached-sasl``) and an optional weight (for prioritizing servers in a cluster; its value is an integer -between ``0`` and ``100`` which defaults to ``XX``; a higher value means more +between ``0`` and ``100`` which defaults to ``null``; a higher value means more priority). Below are common examples of valid DSNs showing a combination of available values:: @@ -201,7 +205,7 @@ Available Options expense of more write traffic. ``recv_timeout`` (type: ``int``, default: ``0``) - Specifies he amount of time (in microseconds) before timing out during an outgoing socket (read) operation. + Specifies the amount of time (in microseconds) before timing out during an outgoing socket (read) operation. When the ``no_block`` option isn't enabled, this will allow you to still have timeouts on the reading of data. Valid option values include ``0`` or *any positive integer*. @@ -275,7 +279,7 @@ Available Options are valid and fit within the design of the protocol being used. .. tip:: - Reference the `Memcached extension`_'s `predefined constants`_ documentation + Reference the `Memcached`_ extension's `predefined constants`_ documentation for additional information about the available options. .. _`Transmission Control Protocol (TCP)`: https://en.wikipedia.org/wiki/Transmission_Control_Protocol diff --git a/components/cache/adapters/pdo_doctrine_dbal_adapter.rst b/components/cache/adapters/pdo_doctrine_dbal_adapter.rst index 539419b39bc..76ac5860e89 100644 --- a/components/cache/adapters/pdo_doctrine_dbal_adapter.rst +++ b/components/cache/adapters/pdo_doctrine_dbal_adapter.rst @@ -2,6 +2,8 @@ single: Cache Pool single: PDO Cache, Doctrine DBAL Cache +.. _`pdo-doctrine-adapter`: + PDO & Doctrine DBAL Cache Adapter ================================= @@ -10,19 +12,35 @@ PDO & Doctrine DBAL Cache Adapter The PDO & Doctrine DBAL adapter was introduced in Symfony 3.2. -This adapter stores the cached items a SQL database accessed through a PDO or a -Doctrine DBAL connection:: +This adapter stores the cache items in an SQL database. It requires a `PDO`_, +`Doctrine DBAL Connection`_, or `Data Source Name (DSN)`_ as its first parameter, and +optionally a namespace, default cache lifetime, and options array as its second, +third, and forth parameters:: use Symfony\Component\Cache\Adapter\PdoAdapter; $cache = new PdoAdapter( + // a PDO, a Doctrine DBAL connection or DSN for lazy connecting through PDO $databaseConnectionOrDSN, + // the string prefixed to the keys of the items stored in this cache $namespace = '', - // in seconds; applied to cache items that don't define their own lifetime - // 0 means to store the cache items indefinitely (i.e. until the database is cleared) + + // the default lifetime (in seconds) for cache items that do not define their + // own lifetime, with a value 0 causing items to be stored indefinitely (i.e. + // until the database table is truncated or its rows are otherwise deleted) $defaultLifetime = 0, + // an array of options for configuring the database connection $options = array() ); + +.. tip:: + + When passed a `Data Source Name (DSN)`_ string (instead of a database connection + class instance), the connection will be lazy-loaded when needed. + +.. _`PDO`: http://php.net/manual/en/class.pdo.php +.. _`Doctrine DBAL Connection`: https://github.com/doctrine/dbal/blob/master/lib/Doctrine/DBAL/Connection.php +.. _`Data Source Name (DSN)`: https://en.wikipedia.org/wiki/Data_source_name diff --git a/components/cache/adapters/proxy_adapter.rst b/components/cache/adapters/proxy_adapter.rst index 7fe734834ae..86b24ead50f 100644 --- a/components/cache/adapters/proxy_adapter.rst +++ b/components/cache/adapters/proxy_adapter.rst @@ -5,15 +5,32 @@ Proxy Cache Adapter =================== -This adapter is useful to integrate in your application cache pools not created -with the Symfony Cache component. As long as those cache pools implement the -``CacheItemPoolInterface`` interface, this adapter allows you to get items from -that external cache and save them in the Symfony cache of your application:: +This adapter wraps a `PSR-6`_ compliant `cache item pool interface`_. It is used to integrate +your application's cache item pool implementation with the Symfony :ref:`Cache Component ` +by consuming any implementation of ``Psr\Cache\CacheItemPoolInterface``. +This adapter expects a ``Psr\Cache\CacheItemPoolInterface`` instance as its first parameter, +and optionally a namespace and default cache lifetime as its second and third parameters:: + + use Psr\Cache\CacheItemPoolInterface; use Symfony\Component\Cache\Adapter\ProxyAdapter; - // ... create $nonSymfonyCache somehow - $cache = new ProxyAdapter($nonSymfonyCache); + $psr6CachePool = \\ create your own cache pool instance that implements the PSR-6 + \\ interface `CacheItemPoolInterface` + + $cache = new ProxyAdapter( + + // a cache pool instance + CacheItemPoolInterface $psr6CachePool, + + // a string prefixed to the keys of the items stored in this cache + $namespace = '', + + // the default lifetime (in seconds) for cache items that do not define their + // own lifetime, with a value 0 causing items to be stored indefinitely (i.e. + // until the cache is cleared) + $defaultLifetime = 0 + ); -The adapter accepts two additional optional arguments: the namespace (``''`` by -default) and the default lifetime (``0`` by default). +.. _`PSR-6`: http://www.php-fig.org/psr/psr-6/ +.. _`cache item pool interface`: http://www.php-fig.org/psr/psr-6/#cacheitempoolinterface diff --git a/components/cache/adapters/redis_adapter.rst b/components/cache/adapters/redis_adapter.rst index 87a7386b6ee..bccd37657f0 100644 --- a/components/cache/adapters/redis_adapter.rst +++ b/components/cache/adapters/redis_adapter.rst @@ -2,33 +2,144 @@ single: Cache Pool single: Redis Cache +.. _`redis-adapter`: + Redis Cache Adapter =================== -This adapter stores the contents in the memory of a Redis server. Unlike the APCu -adapter, it's not limited to the shared memory of the current server, so you can -store contents in a cluster of servers if needed. +This adapter stores the values in-memory using one (or more) `Redis server`_ instances. +Unlike the :ref:`APCu adapter `, and similarly to the +:ref:`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``. -It requires to have installed Redis and have created a connection that implements -the ``\Redis``, ``\RedisArray``, ``\RedisCluster`` or ``\Predis`` classes:: +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:: use Symfony\Component\Cache\Adapter\RedisAdapter; $cache = new RedisAdapter( + // the object that stores a valid connection to your Redis system \Redis $redisConnection, + // the string prefixed to the keys of the items stored in this cache $namespace = '', - // in seconds; applied to cache items that don't define their own lifetime - // 0 means to store the cache items indefinitely (i.e. until the Redis memory is deleted) + + // the default lifetime (in seconds) for cache items that do not define their + // own lifetime, with a value 0 causing items to be stored indefinitely (i.e. + // until RedisAdapter::clear() is invoked or the server(s) are purged) $defaultLifetime = 0 ); +Configure the Connection +------------------------ + The :method:`Symfony\\Component\\Cache\\Adapter\\RedisAdapter::createConnection` -helper method allows creating a connection to a Redis server using a `Data Source Name (DSN)`_:: +helper method allows creating and configuring the Redis client class instance using a +`Data Source Name (DSN)`_:: + + use Symfony\Component\Cache\Adapter\RedisAdapter; + + // pass a single DSN string to register a single server with the client + $client = RedisAdapter::createConnection( + 'redis://localhost' + ); + +The DSN can specify either an IP/host (and an optional port) or a socket path, as well as a user +and password and a database index. + +.. note:: + + A `Data Source Name (DSN)`_ for this adapter must use the following format. + + .. code-block:: text + + redis://[user:pass@][ip|host|socket[:port]][/db-index] + +Below are common examples of valid DSNs showing a combination of available values:: + + use Symfony\Component\Cache\Adapter\RedisAdapter; + + // host "my.server.com" and port "6379" + RedisAdapter::createConnection('redis://my.server.com:6379'); + + // host "my.server.com" and port "6379" and database index "20" + RedisAdapter::createConnection('redis://my.server.com:6379/20'); + + // host "localhost" and SASL use "rmf" and pass "abcdef" + RedisAdapter::createConnection('redis://rmf:abcdef@localhost'); + + // socket "/var/run/redis.sock" and SASL user "user1" and pass "bad-pass" + RedisAdapter::createConnection('redis://user1:bad-pass@/var/run/redis.sock'); + +Configure the Options +--------------------- + +The :method:`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:: + + use Symfony\Component\Cache\Adapter\RedisAdapter; + + $client = RedisAdapter::createConnection( + + // provide a string dsn + 'redis://localhost:6739', + + // associative array of configuration options + array( + 'persistent' => 0, + 'persistent_id' => null, + 'timeout' => 30, + 'read_timeout' => 0, + 'retry_interval' => 0, + ) + + ); + +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. + +``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. - $redisConnection = RedisAdapter::createConnection('redis://localhost'); +``timeout`` (type: ``int``, default: ``30``) + Specifies the time (in seconds) used to connect to a Redis server before the + connection attempt times out. -See the method's docblock for more options. +.. note:: + When using the `Predis`_ library some additional Predis-specific options are available. + Reference the `Predis Connection Parameters`_ documentation for more information. .. _`Data Source Name (DSN)`: https://en.wikipedia.org/wiki/Data_source_name +.. _`Redis server`: https://redis.io/ +.. _`Redis`: https://github.com/phpredis/phpredis +.. _`RedisArray`: https://github.com/phpredis/phpredis/blob/master/arrays.markdown#readme +.. _`RedisCluster`: https://github.com/phpredis/phpredis/blob/master/cluster.markdown#readme +.. _`Predis`: https://packagist.org/packages/predis/predis +.. _`Predis Connection Parameters`: https://github.com/nrk/predis/wiki/Connection-Parameters#list-of-connection-parameters From 7db929c2e8a6b862a0209490a78c0eb5be99ce01 Mon Sep 17 00:00:00 2001 From: Rob Frawley 2nd Date: Wed, 8 Feb 2017 14:19:13 -0500 Subject: [PATCH 4/4] corrected spelling/grammar --- components/cache/adapters/apcu_adapter.rst | 4 ++-- components/cache/adapters/chain_adapter.rst | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/components/cache/adapters/apcu_adapter.rst b/components/cache/adapters/apcu_adapter.rst index e4b052b231b..e064b6c9814 100644 --- a/components/cache/adapters/apcu_adapter.rst +++ b/components/cache/adapters/apcu_adapter.rst @@ -10,7 +10,7 @@ APCu Cache Adapter This adapter is a high-performance, shared memory cache. It can increase the application performance very significantly because the cache contents are stored in the shared memory of your server, a component that is much faster than -others, such as the file system. +others, such as the filesystem. .. caution:: @@ -46,7 +46,7 @@ parameter:: .. tip:: - Note that this adapters CRUD operations are specific to the PHP SAPI it is running + Note that this adapter's CRUD operations are specific to the PHP SAPI it is running under. This means adding a cache item using the CLI will not result in the item appearing under FPM. Likewise, deletion of an item using CGI will not result in the item being deleted under the CLI. diff --git a/components/cache/adapters/chain_adapter.rst b/components/cache/adapters/chain_adapter.rst index b74bd2048a2..f3d5cfc0253 100644 --- a/components/cache/adapters/chain_adapter.rst +++ b/components/cache/adapters/chain_adapter.rst @@ -25,12 +25,12 @@ maximum cache lifetime as its second parameter:: .. note:: - When an item is not found in the first adapters but is found in the next ones, this + When an item is not found in the first adapter but is found in the next ones, this adapter ensures that the fetched item is saved in all the adapters where it was previously missing. -The following shows how to create a chain adapter instance using the fastest and slowest -storage engines, :class:`Symfony\\Component\\Cache\\Adapter\\ApcuAdapter` and +The following example shows how to create a chain adapter instance using the fastest and +slowest storage engines, :class:`Symfony\\Component\\Cache\\Adapter\\ApcuAdapter` and :class:`Symfony\\Component\\Cache\\Adapter\\FilesystemAdapter`, respectfully:: use Symfony\Component\Cache\Adapter\ApcuAdapter;