Installing memcached on ubuntu

Memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.
Memcached on Ubuntu has two components. A standalone program running on your server and a client PHP extension.
To install memcached, run the following command:

sudo aptitude install memcached php5-memcache php-pear
.....
Creating config file /etc/php5/conf.d/memcache.ini with new version
sudo aptitude install php5-dev  libmemcached-dev
sudo pecl install Memcache
.....
Installing '/usr/lib/php5/20090626+lfs/memcache.so'

Please choose

Enable memcache session handler support? [yes] : yes

Find your php.ini file and execute following command

php -i | grep php.ini
nano /etc/php5/apache2/php.ini

Add the line to the bottom of the file: memcache.hash_strategy=”consistent”

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

If you get a message saying, “can’t run as root without -u switch” then try this:

memcached -d -u www-data -m 1024 -l 127.0.0.1 -p 11211

To active new configuration execute following command

/etc/init.d/apache2 restart
/etc/init.d/memcached restart

Verify memcached

pgrep -fl memcached
netstat -an | grep 11211

Check memcached status

memcached -u www-data -vv
ps -A | grep memcached

There are either procedural, or object oriented functions already available. Here is an example of a script which will store a simple variable and then retrieve it and display it.

/* procedural API */
if (class_exists('Memcache')) {
    $memcache = new Memcache;
	try {
	 /* connect to memcached server */
	$memcache_obj = memcache_connect('localhost', 11211);
	} catch (Exception $e) { print_r($e);}
	if ($memcache_obj) {
	/*set value of item with key 'var_key' using 0 as flag value,
         * compression is not used expire time is 30 seconds*/
	memcache_set($memcache_obj, 'var_key', 'some variable', 0, 30);
	echo memcache_get($memcache_obj, 'var_key');
	}
}

I’d recommend downloading memcache.php which is a php script showing you a lot of useful information about your memcached servers. Once downloaded, put it in a web facing directory on your server, and modify the $MEMCACHE_SERVERS array with your server addresses.

This entry was posted in Debian&Ubuntu. Bookmark the permalink.