Thursday 20 March 2014

Using MEMCACHE for caching PHP Website for increasing Website Speed

In the case of  Large dynamic websites, it may become slower for some pages where it has to fetch large data from the database. So Solution in PHP is using the PHP cache methods.
Their are many cache tools available for php sites. Some of them are:-


  • APC 
  • Xcache
  • Memcache
  • E Accelerator .etc.
In this Post I will explain how to use memcache & its basic functions. I know that their are many vast tutorials explaining this but am just trying to figure out basic functions for new programmers.
Try to install memcache in your windows or linux or Mac by any methods. Iam not covering the installation process here.So I hope that your memcache is installed in your system & you are ready for the magic.


Many common processes utilized in web application development (for example generating large amounts of HTML or fetching data via complex SQL queries) are processor and disk intensive. Serializing and caching the generated data to disk solves the first of those problems, but you still get a small performance hit each time you read the data to disk, plus you have to write routines to automatically purge old cached data. 
Memcached solves this problem for you by letting you write frequently accessed data directly to RAM, where it can be fetched almost instantaneously; plus you can tell memcached how long to store the cached data and it will automatically purge stale data without any further intervention from you, the programmer. 
Many web sites & applications such as Facebook, LiveJournal, Flickr, Slashdot, WikiPedia/MediaWiki, SourceForge, Digg and Twitter use memcached to enhance their performance. 

What is Memcached? 
Memcached (Memory Cache Daemon) was developed by the team at LiveJournal to improve performance of their social blogging site by minimizing the impact of the bottleneck caused by reading data directly from the database. Memcached is a server that caches Name Value Pairs in memory. The “Name”, or key, is limited to 250 characters, and the “Value” is limited to 1MB in size. Values can consist of data, HTML 
Fragments, or binary objects; almost any type of data that can be serialized and fits in memcached can be stored.

Drawbacks/Limitations to Memcached 
• Memcached is not a persistent data storage mechanism. The data cannot be 
queried SQL-style or dumped to disk; the only way to access the information in Memcached is retrieve the data from the server via the correct key (or “Name”) for the information stored. There is no fail-over/high availability support; if a memcached server goes down or the service is restarted, the data is gone. 
• In many cases there is much less RAM available than disk space, so the amount of 
memory you can dedicate to memcached is more than likely fairly limited. 
• Things like resource variables (file handles, etc.) and internal PHP classes cannot 
be stored using memcached, because they cannot be serialized.


Initializing memcache


PHP provides both procedural and object-oriented interfaces to memcached. My 
examples will use the object-oriented interface. If you're interested in using the 
procedural interface, consult the PHP manual (http://www.php.net/memcache). 
We'll assume that our memcached instance is listening on localhost on port 12345. 
 $cache = new Memcache(); 
$cache->connect('localhost', 12345);

Before you start storing data, you'll want to make sure that you actually were able to 
connect to the memcached instance. 
 if ($cache->getServerStatus() == 0) die('Could not connect to 
 memcached!'); 

In memcache you have the power to add more than one server, so we can add server by:-

$cache->addServer('mem1.domain.com'1121133);$cache->addServer('mem2.domain.com'1121167);

Or Adding servers using an array

$servers = array(
    array(
'mem1.domain.com'1121133),
    array(
'mem2.domain.com'1121167)
);
$cache->addServers($servers);

But in this case if we didn't check before adding The same server may appear multiple times in the server pool, because no duplication checks are made. This is not advisable; instead, use the weight option to increase the selection weighting of this server.

So we can code something Like this :-
$server=$cache->getServerList();


foreach ($servers as $server) 
       if($server['host'] == $host and $server['port'] == $port) //checking whether server already added
               //already exist
//code here 
                } 
But Since we are talking about only one server our previous connect method is enough.


Flush all cache data

You may also at some point want to flush the cache without restarting the service: 
 $cache->flush();


Storing Data 
The next step is to actually store some data in the memcached instance. Each bit of data you store will be identified by a unique "key." You'll need to be sure that you don't use the same key to store two different bits of data; if you do, the second bit will overwrite the first, as you might expect. 
 $mydata = array( 
'user_id' => 1234,
 'fullname' => 'John Doe',
 'phone' => '(123) 234-3456' 
); 
$cache->set('my-memcached-key', $mydata, MEMCACHED_COMPRESSED, 
 1500); 
$cache->set('uncompressed-data', 'Just a string ...', null, 0); 
Now you've stored the contents of $mydata in the cache! 
The third and fourth options in the set() method specify whether or not to compress the cached data using zlib (use null for no compression) and how long in milliseconds to keep the cached data (use 0 for no expiration) respectively. Remember that setting no expiration date doesn't mean that the data will be cached forever ... if memcached runs out of memory it will start to remove old data, even data with no expiration date. 

Retreiving and Replacing Data

Retrieving cached data is very straightforward; you do need to remember to let 
memcached know if the data you are fetching was compressed. 
 echo $cache->get('my-memcached-key', MEMCACHED_COMPRESSED); 
echo $cache->get('uncompressed-data'); 
If you want to replace cached data, you've got two options. First, you can use the 
Memcache::replace() function, which will return false and not store your data if the 
cache key does not exist, or you can use Memcache::set(), which will replace the data if 
it exists, and store the value if it does not exist. 
 $cache->replace('uncompressed-data', 'New Value', null, 1500); 
or $cache->set('uncompressed-data', 'New Value', null, 1500); 

But In my opinion using set is more secure than using replace.

Deleting data

Deleting data is also straightforward ... 
 $cache->delete('my-memcached-key');


Incrementing and Decrementing Numeric Values 
Memcached also provides the Memcache::increment() and Memcache::decrement() 
methods for increasing or decresing the value of cached numeric values by a certain 
value. These funtions will NOT create the value if it does not exist, though. 
 $cache->set('connection-count', 1, null, 60000); $cache->increment('connection-count', 1); 
$cache->decrement('connection-count', 1); 

To append data to a variable

For adding data to a already existing cache method,we can use append method.
For eg: if we set variable name like:-

$cache->set('varname',$data);
$cache->append('varname',$moredate);


Sample Usage of memcache

$cache=new Memcache();
$cache->connect('localhost',1235);
$ip=$cache->get('data');
if(!$ip){
if($cache->getResultCode()==Memcached:RES_NOTFOUND){
$data_db=getdata();// fetch data from db
$cache->set('data',$data_db);

}
}else{
$ip=$cache->get('data');
echo $ip;

}


No comments:

Post a Comment