Aug 21 2008

Using Memcached with PHP

Category: PHPBipin Balakrishnan @ 11:59 am

Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications by caching the frequently accessed data.By default, memcached uses the port 11211.

Danga Interactive developed memcached to enhance the speed of LiveJournal.com , a site which was already doing 20 million+ dynamic page views per day for 1 million users with a bunch of webservers and a bunch of database servers. memcached dropped the database load to almost nothing, yielding faster page load times for users, better resource utilization, and faster access to the databases.

The system is used by several very large, well-known sites including YouTube, LiveJournal, Slashdot, Wikipedia, SourceForge, ShowClix, GameFAQs, Facebook, Digg, Twitter, Fotolog, BoardGameGeek, NYTimes.com, deviantART, Jamendo, Kayak and in our Mobshare too.

Installing and Configuring Memcache

sudo apt-get install memcached
sudo apt-get install php5-memcache

Configuration Files

edit sudo vim /etc/php5/apache2/conf.d/memcache.ini or

sudo vim /etc/php5/cli/conf.d/memcache.ini //for cli apps

; uncomment the next line to enable the module
extension=memcache.so

[memcache]
memcache.dbpath="/var/lib/memcache"
memcache.maxreclevel=0
memcache.maxfiles=0
memcache.archivememlim=0
memcache.maxfilesize=0
memcache.maxratio=0

Edit sudo vim /etc/memcached.conf to change the default configuration settings

Restart apache webserver

starting memcached

sudo /etc/init.d/memcached start

To see storing session on memcache on the terminal use

sudo memcached -vv

Eg 1: Using memcache in PHP

Testing Program whether it properly got installed and working fine

<?php
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
$version = $memcache->getVersion();
echo "Server's version: ".$version."<br/>\n";
$tmp_object = new stdClass;
$tmp_object->str_attr = 'test';
$tmp_object->int_attr = 123;
$memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");
echo "Store data in the cache (data will expire in 10 seconds)<br/>\n";
$get_result = $memcache->get('key');
echo "Data from the cache:<br/>\n";
var_dump($get_result);
?>

Outputs this as result

Server's version: 1.2.1<br/>
Store data in the cache (data will expire in 10 seconds)<br/>
Data from the cache:<br/>
object(stdClass)#3 (2) {
  ["str_attr"]=>
  string(4) "test"
  ["int_attr"]=>
  int(123)
}

Example 2: Using in database access

<?php
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
mysql_pconnect("localhost","root","");
mysql_select_db("bestofferIVR");
//Write your time consuming query here
$key = md5("SELECT * FROM callerinfo where cnumber='9941426932'");
$get_result = $memcache->get($key);
if ($get_result) {
print_r($get_result);
echo "If condition Working";
}
else {
 // Run the query and transform the result data into your final dataset form
 $qurey="SELECT * FROM callerinfo where cnumber='9941426932';";
 $result = mysql_query($qurey);
 $row = mysql_fetch_array($result);
 print_r($row);
 $memcache->set($key, $row, TRUE, 86400); // Store the result of the query for a day
 echo "Else condition Working";
}
?>

On the First Run the output will be as below, ie directly fetcing from the DB

Array
(
    [0] => 5
    [id] => 5
    [1] => 9941426932
    [cnumber] => 9941426932
    [2] => 2008-03-20 08:28:57
    [time] => 2008-03-20 08:28:57
    [3] => mal12
    [scheme] => mal12
)
Else condition Working

From the second run onwards the result will be as below ie using the memcache not DB

Array
(
    [0] => 5
    [id] => 5
    [1] => 9941426932
    [cnumber] => 9946426932
    [2] => 2008-03-20 08:28:57
    [time] => 2008-03-20 08:28:57
    [3] => mal12
    [scheme] => mal12
)
If condition Working

Tags: , , , , ,

4 Responses to “Using Memcached with PHP”

  1. iamatechie says:

    This is informative. Does this memcached server an overhead for the IVR server ? Sometimes it may be. It is more advisable to backup and clear database data periodically (for instance 6 months). This will really add up database speed and with memchached the application really rocks.

  2. admin says:

    Ya it got worked.The thing you told is different .I had written here only an example of its usage.Our need is to select the schemes of the vodafone customers calling to our IVR which contain 34lakh record and not for taking the report.So back up case will not work.Yes for taking reports your idea will work.

  3. varundbest says:

    I liked what you posted here but I must say that it can be improved, although it is good but some more effort can get this blog to the top. And the theme is good.

  4. God of War says:

    Greetings, I view all your posts, keep them coming.

Leave a Reply