Memcache is a high performance distributed in-memory object caching which improves the website performance by caching the frequently used data. The data might be strings,objects from results of database calls, API calls, or page rendering.
Take an example of simple scenario. Suppose you have a blog users access your website for reading blog. Every time the blog post of your website renders it fetches data from database. Memcache cache this data in RAM so that every time your website page open it won’t run sql queries to fetch data from DB.
How Memcache Improves Website Performance
Memcache speed up the loading time of dynamic website by alleviating the database load. Retrieving same data again and again from database takes resources as well as time so for read operation we can use the Memcache which save the data in cache(in system RAM).
How to Install Memcache in Ubuntu
To install memcache in ubuntu run the following command
1 |
sudo apt-get install memcached |
once memcache is install you can set the configuration
1 |
vi /etc/memcached.conf |
By default caching memory and port is
-m 64 //64 MB
-p 11211
Set as per requirement.
You can check whether memcached service is running or not by using
1 |
sudo service memcahed status |
How to use Memcache For PHP
// To use memcache for your php project first of all define host and port
define(‘HOST’, ‘127.0.0.1’);
define(‘PORT’, ‘11211’);
// Create Connection
$memcache = new Memcache;
$cacheAvailable = $memcache->connect(HOST, PORT);
Function which we use for memcache
Get() – get the value for a specified key
Set() – sets a given key with a given value
Add() – add values to the cache if it is not exists
Replace() – sets datas into cache if key already exists
Flush() – removes all keys and cached data
Get more information about Memcache function on php.net manual