Memcached is an open source distributed memory caching system. It is used for speeding up dynamic web applications by reducing database load. In other words, every time a database request is made it adds additional load to the server. Memcached reduces that load by storing data objects in dynamic memory (think of it as short-term memory for applications). Memcached stores data based on key-values for small arbitrary strings or objects including:
- Results of database calls
- API calls
- Page rendering
Memcached was initially developed by Brad Fitzpatrick in 2003 and is now used by Facebook, Twitter, YouTube, Wikipedia, and other big and small web applications.
How it Works
Memcached uses a client-server architecture based on four components:
- A client-server, which retains the list of available Memcached servers
- A client-based hashing algorithm, which picks up a server based on the requested “key.“
- A server software, which stores the combinations of values + key into an internal hash table
- A Least Recently Used (LRU) algorithm, which decides when to use old data or the memory
Memcached works like other caching systems, but now the database is at the core of the process. Let’s see the workflow in five quick steps:
- The client-server receives a query from a user (i.e., access to a specific URL of a website with an HTTPS redirect);
- The client-server checks with the Memcached server if the data needed is already stored in its memory;
- If the data exists, Memcached directly returns it to the client server;
- If the data isn’t already saved in the cache, Memcached forwards the request to the database;
- Requested data is now forwarded to the client-server and, at the same time, the Memcache index is updated with these latest values: the cache is now ready to be used in the future (see step 3).
How to install Memcached (CentOS/REHL 7+)
First we will install Memcached server on our system. Use the following command to install memcached using yum package manager.
yum install memcached
Next we want to start and enable memcached.
systemctl enable memcached systemctl start memcached
Now we have installed Memcached server on our system. But to use Memcached service using php scripts we need to install Memcache php extension. So first install php and other required php modules and then use PECL to install PHP Memcache extension using following commands.
Are you using Plesk? Stop here and follow this guide instead.
yum install gcc glibc-devel libmemcached-devel zlib zlib-devel
Install php-pear/pecl extension, lets update pecl-channel while we’re at it:
yum install php php-devel php-pear pecl channel-update pecl.php.net
install memcache module w/ pecl:
pecl install memcached
Finally enable memcached module, you can either add the "extension=memcached.so"
line to php.ini or execute command:
echo "extension=memcache.so" > /etc/php.d/memcached.ini
Add comment