Book Image

Getting Started with Memcached

By : Ahmed Soliman
Book Image

Getting Started with Memcached

By: Ahmed Soliman

Overview of this book

<p>Web application performance is no longer a non-functional requirement, but an implicit condition for an engaging user experience. As a result, responsive and highly scalable applications are becoming a necessity. Memcached is a high-performance distributed memory caching system built to speed up dynamic web applications by offloading pressure from your database. <br /><br />Getting Started with Memcached is a hands-on, comprehensive guide to the Memcached service and it’s API in different programming languages. It contains practical recipes to integrate Memcached within your Rails, Django, or even Scala Play! applications.<br /><br />This book will show you everything you need to know to start using Memcached in your existing or new web applications.<br />This book uses real-world recipes to help you learn how to store and retrieve data from your clustered virtual memory cache pool and how to integrate caching into your favourite web development framework.</p> <p><br />You will also learn how to build a Memcached consistent-hashing scalable cluster and how Memcached clients are properly configured to use different servers to scale out your memory cache pool in Ruby, Python, PHP, and Java. With this book, you will see how to cache templates and database queries in the most popular web development framework in use today.</p>
Table of Contents (9 chapters)

Using memcached with PHP (Intermediate)


There are basically two memcached clients for PHP right now (memcache, and memcached), note the d at the latter. The memcache extension is older, lightweight, and most commonly used, and easier to install. The memcached module is feature-rich but still not widely adopted.

For the sake of simplicity, we will be using the memcache PHP extension in this recipe.

PHP is one of the most popular languages used for Web development today, it's very likely that you are actually using many pieces of software written in PHP on a daily basis without knowing.

Getting ready

I'm assuming you are using Ubuntu; you will need to have the simple setup of apache2 and php5. It's simple to get this stack working using this command:

sudo apt-get install apache2 php5

First, we need to install the PHP memcache extension using apt-get:

sudo apt-get install php5-memcache

This automatically installs the extension and gets everything wired and configured for you, if you want to use the memcached extension instead, all you need to do is to replace php5-memcache with php5-memcached and voila, everything just works!

If you are using Mac OS X, it's a slightly different story, and you will need to install apache2 and php5.

One of the quickest ways to do so is to install a nice package called MAMP (http://www.mamp.info/en/index.html); it will make life a lot easier for you. But, if you are an advanced user and want to go with the more manual route, you get really detailed instructions to get your OS X setup ready with Apache, MySQL, and PHP ready at (http://jason.pureconcepts.net/2012/10/install-apache-php-mysql-mac-os-x/).

How to do it...

  1. First, we are going to start with a connection test to the memcached daemon:

    <?php
        $memcache = new Memcache;
        $memcache->connect('localhost', 11211) or die ("Could not connect");
    
        $version = $memcache->getVersion();
        echo "Server's version: ".$version."<br/>\n";
    ?>
  2. The output of this script actually depends on the current version of the memcached server running, in my case the output is:

    Server's version: 1.4.13
  3. Next, let's set and get some keys from the connected memcached server:

    <?php
        $memcache = new Memcache;
        $memcache->connect('localhost', 11211) or die ("Could not connect");
    
        $sample_obj = new stdClass;
        $sample_obj->str_attr = 'Memcache in PHP is cool';
        $sample_obj->int_attr = 2468;
    
        $memcache->set('sample_user', $sample_obj, false, 15) or die ("Failed to store data in memcached");
        echo "Data stored in Memcached (will expire in 15 seconds)<br/>\n";
    
        $get_result = $memcache->get('sample_user');
        echo "Object from the cache:<br/>\n";
    
        var_dump($get_result);
    
    ?>

How it works...

First, we are creating the Memcache object, that's the object we will be using to communicate with our memcached server in an object-oriented manner.

Then, we initialize the connection to the memcached server using the connect method that has the following signature which takes the host, port, and connection timeout:

bool Memcache::connect ( string $host [, int $port [, int $timeout ]] )

The connect method closes the connection to the memcached server automatically at the end of the execution of the script.

Then, we used the getVersion method to retrieve the version of the memcached server we are connected to. We are using this method only to test our connection to the memcached server.

We then moved to the real work, we created an instance of the stdClass of PHP and added two attributes to the object to serialize and store in memcached under the key "sample_user"; We set the timeout to 15 seconds, this means that the memcached server will delete the key after 15 seconds. We also used false for flags, since we don't need compression or any other setting at the moment.

Then, we retrieved the value back from memcached using the get method of the Memcache object, and then we printed it on the screen. The output of the script would be as follows:

Data stored in cached (will expire in 15 seconds)Object from the cache:object(stdClass)#3 (2) { ["str_attr"]=> string(23) "Memcache in PHP is cool" ["int_attr"]=> int(2468) }

There's more...

If you are planning to connect to a cluster of memcached servers you will need to add all the servers using the addServer method:

<?php

/* OO API */
$memcache = new Memcache;
$memcache->addServer('memcached_host1', 11211);
$memcache->addServer('memcached_host2', 11211);
?>

Then, start using your memcache instance as usual and the magic will happen.