Is your Memcached instance working correctly? Who the hell knows? Well, we will in a minute.
Open your terminal, and use the ancient telnet to connect to your server on the correct port (usually 11211):
$ telnet my.memcache.server.net 11211
Connected to my.memcache.server.net.
Escape character is '^]'.
Next we reset existing stats then turn on stats collection:
stats detail on
Now, make a request on your website that will call memcache.
Finally, turn stats collection off, then dump the stats collected. If you have output, your memcached server is successfully caching your keys!
stats detail off
stats detail dump
PREFIX User get 3 hit 2 set 1 del 0
PREFIX Trade get 1 hit 0 set 1 del 0
PREFIX Currency get 1 hit 0 set 0 del 0
PREFIX Orders get 2 hit 0 set 2 del 0
PREFIX Prices get 2 hit 0 set 0 del 0
To get out of telnet, you type quit.
So I pushed my changes to the production repository, only to discover that Memcache wasn’t installed on the server at work (a cPanel installation running over CentOS(6 i think)). Time to install it then!
in the terminal, get memcached installed. Nice n easy.
sudo yum install memcached
Then launch it!
memcached -d -u nobody -m 512 -p 11211 127.0.0.1
Then install memcache PHP extension. You do this in cPanels WHM. Search module installers in WHM
In Find a PHP Pecl, type memcache, and get it installed! You may or may not have to restart apache, but go to a phpinfo() and you should now see it running on your system!
See my previous post for how to use memcache in your PHP 🙂
Caching can really help speed matters on on a webpage. Especially when you have a big ass property search going on with umpteen joins etc. Sometimes it’s just easier to cache the results (for a suitably reasonable time). So lets do just that. If you haven’t got memcache installed, search my blog for my post manually compiling php modules successfully (justr search ‘successfully’). Once you’ve done that, it’s a piece of cake!
$cache_key = $area;
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
$cache_value = $memcache->get($cache_key);
$db = new Application_Model_DbTable_Property();
$props = $db->areaSearch($area);
$cache_value = $props->count();
$memcache->set($cache_key, $cache_value, false, (60*60*24)) or die ("Failed to save data at the server");
And thats it! We give each query we need a unique key, in the example it is whatever $area is (Scotland!) and try to retrieve it. If there is nothing returned, we do our query and store the result. The 60*60*24 (thats in seconds by the way) is the time until the cache expires, upon which it will return nothing again and refresh the query and cache. It really is that easy! Have fun!