Tuesday, December 16, 2014

Memcache and PHP

In this post I'm going to use PHP Memcache module as an interface to memcached. If you need to reduce the database load for your webapp this approach seems pretty cool.

I assume you have already installed PHP/MySQL and a compiler on your machine. You can install "build-essential" in order to install Memcache.
sudo apt-get install build-essential

Install php5-memcache
sudo apt-get install php5-memcache

Install Memcache daemon
sudo apt-get install memcached

Install PHP Pear
sudo apt-get install php-pear
Add Memcache using PECL module
sudo pecl install memcache
Update memcache.ini using following,
extension=memcache.so
Verify  Memcache installation

i) Try telnetting to your Memcache instance using,
telnet localhost 11211
ii) phpinfo()



Lets write our first simple PHP script,
<?php
$memcache = new Memcache();
$memcache->addServer('localhost', 11211) or die ("Could not connect");
$key = md5('my-name'); // Unique key
$cache_result = array();
$cache_result = $memcache->get($key); // Memcached object
if($cache_result){
// Second Request
$demos_result=$cache_result;
echo "Result found in memcache\n";
}else{
// Initial Request
$name= "Udara R";
$memcache->set($key, $name);
echo "Result not found in memcache, added to the memcache \n";
}
echo $cache_result."\n";
?>
So here I'm using md5 value of the "my-name" string as the key, you can use unique ID (UUID)  while storing values in Memcache.
$key = md5('my-name');

Then I'm trying to retrieve existing value attached to my key,
$cache_result = $memcache->get($key);
If we are unable to retrieve anything from Memcache, then set key-value pair using,
$memcache->set($key, $name);
Our objective is to reduce the database load in this post, so we can interrupt our data retrieve logic to find relevant data in Memcache first, then query from database and put in to the cache layer, if not exists.

No comments:

Post a Comment