Setup and configure memcached on a linux PHP webserver

Monday, August 23rd, 2010 at 12:44 am | Tutorials

This is my short tutorial of how to set up, use and monitor memcached on a PHP web server.

My webserver is a CentOS 5 webserver with cPanel.

Setup memcached

1. Setup libevent

This is a library needed by memcached. Install it:

wget http://monkey.org/~provos/libevent-1.4.14b-stable.tar.gz
tar zxvf libevent-1.4.14b-stable.tar.gz
cd libevent-1.4.14b-stable
./configure
make
make install
cd ..

2. Setup memcached

Get and install the latest memcached code:

wget http://memcached.org/latest
tar -zxvf memcached-1.x.x.tar.gz
cd memcached-1.x.x
./configure --with-lib-event=/usr/local/
make
make install

3. Add the libevent library to the path

If you attempt to run memcache at this point you will probably get an error for missing the libevent library. Register it:

touch /etc/ld.so.conf.d/libevent-i386.conf
echo "/usr/local/lib/" > /etc/ld.so.conf.d/libevent-i386.conf
ldconfig

4. Test memcached

memcached -d -m 1024 -u root -l 127.0.0.1 -p 11211

This opens up memcached server with 1024MB of RAM on port 11211.  (memcached -h for more on options)

Connect via telnet to make sure it’s up:

telnet localhost 11211

Ctrl-C to exit. Done.

Setup the PECL extension for PHP

1. Setup PECL memcached

pecl install memcached

Careful: Notice the “d” at the end. Pecl also hosts an extension called “memcache”. This is a different implementation. All the examples listed below use “memcached”.

Add this line to your php.ini:

extension = “memcache.so”

2. Test the installation

Create a new PHP file within your document root directory with the following contents:

<?php
$memcache = new Memcache;

// Connect
if(!$memcache->connect('localhost', 11211)) {
 die('Could not connect to server');
}

// Set the cache
$memcache->set("test_hash", "It works, mate!", false, 400);

// Get the cache
if ($ret = $memcache->get("test_hash")) {
 echo $ret;
}
else {
 die('Could not retrieve data from memcached');
}
?>

Save it and point your browser to this file.

You should get: “It works, mate!”

For more information on how to use memcached, check out the memcached manual pages.

Further steps

Starting memcached as a service

Check out this tutorial by Danny Bembibre.

Monitoring memcached

This has given me some hard time.

There are all sorts of tools to monitor the cache, some are web-based, some are local applications. I’ve had tough luck finding something that I could recommend.

The only one I’m currently using is a top-like command line tool named: memcache-top.

To install and run it:

wget http://memcache-top.googlecode.com/files/memcache-top-v0.6
chmod +x memcache-top-v0.6
./memcache-top-v0.6

That’s all. I hope this will be useful to all you out there.

If you have any comments please do not hesitate to contact me.

Be Sociable, Share!

Tags: , ,

Leave a Reply