Monday, March 1, 2010

Installing memcached on CentOS 5.x

Memcached is a distributed memory object caching system - as quoted from http://memcached.org/

In other words, it is simply a cache for common database queries and typically reduces database load by caching the mentioned queries.

It is not part of the standard CentOS distro, so installation of the DAG repositories was necessary.

0. Login as root on your webserver(s)

This install specific to the 32-bit version of CentOS 5.x

1. Get the rpmforge rpm (if not already installed)




2. Install the rpmforge rpm
rpm -Uvh rpmforge-release-0.3.6-1.el5.rf.i386.rpm

3. Install memcached and other packages required
yum install --enablerepo=rpmforge memcached php-pecl-memcache


4. Modify php.ini
nano /etc/php.ini

add line under Dynamic Extension section.
;  extension=memcache.so



5. Create memcached configuration file
nano /etc/sysconfig/memcached
Add to file:
#  Specify Port
PORT="11211"
#Specify User for service to run.
USER="memcached"
#Specify maximum number of connections
MAXCONN="2048"
#Set Cache size based on Memory available

CACHESIZE="512"
#Specify which interface to listen to - Security Measure
OPTIONS="-l 127.0.0.1"

6. Add the memcached user (the same username entered in step 5)
useradd memcached

7. Start the memcached daemon and set to automatically start on reboot
service memcached start
chkconfig memcached on


8. Test memcached
Original Script located at http://dorkage.net/2009/02/memcached-test/
Create script in site root, or other preferred location.
touch /var/www/html/memcachedtest.php

Paste the following code:

<?php
//memcached simple test
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
$key = md5('42data');  //something unique
for ($k=0; $k<5; $k++) {
$data = $memcache->get($key);
    if ($data == NULL) {
        $data = array();
        //generate an array of random shit
        echo "expensive query";
        for ($i=0; $i<100; $i++) {
            for ($j=0; $j<10; $j++) {
                $data[$i][$j] = 42;  //who cares
            }
        }
        $memcache->set($key,$data,0,3600);
    } else {
        echo "cached";
    }
}
?>



Run http://yourserver.com/memcachedtest.php to see if it works
You should see "Expensive Query"
If memcached works, you should see "Cached Cached Cached" upon refreshing the page.

-n