Starting up and running Memcached
Memcached is a key value object cache used by many websites to relieve the load on their databases and provide faster answer to the client. it’s very interesting since it needs only commodity PCs and can scale indefinitely. The keys distribution is solely made by your application, a hash function is usually used, thus the different instances share nothing and have no knowledge about each other!
I have installed memcached on my Ubuntu using the ppa, you can right away start your instance, in fact you can start multiple instances of memcached on different ports on your machine. With the following commands I started two instance on 11211 and 11311:
ded@ubuntu:~$ memcached -p 11211 -d
ded@ubuntu:~$ memcached -p 11311 -d
-p is used to specify the listening port, 11211 is the one by default, -d tells Memcached to start as a daemon.
You can test your running memcached instance with Telnet, the following example connect to the instance set a key “key1″to “hello world” then get that key.
Lets connect to the first instance
ded@ubuntu:~$ telnet localhost 11211
Connected to localhost.
Escape character is ‘^]’.
Now we want to store the word “hello” with the key “key1″, the first digit is the flag, the second is the expiry time (0 means unlimited), last is the number of bytes expected (5 for the word hello) if you make a mistake on that you will receive a bad data chunk error message!
set key1 0 0 5
Lets now retrieve that value :
VALUE key1 0 5
we close the connection using :
Connection closed by foreign host.
Next I used libmemcached, a c++ library, to access and use memcached instances. Here I relied on MyCache, a class that Padraig O’Sillivan wrote on his blog. Here is a simple main that make use of the that class to cache a string:
std::string text=”Hello world”; // our string to cache
std::vector raw(text.size()); // Cache objects need to in vector format
MyCache::singleton().set(“key1″,raw); // cache the vector with the key “key1″
std::vector data=MyCache::singleton().get(“key1″); // retrieve the object in a vector
To compile a program that uses libmemcache don’t forget the -lmemcached compiler flag !
g++ -lmemcached -o test test.cc
Note: It’s very easy to write your own MyCache Class it’s just a wrapper of memcache::Memcache, but if you use Padraig’s one you need to specify in the class MyCache the number of instances that you have in num_of_clients. and modify the GetCache() method that randomly select a client, with a deterministic one, since you’ll need to retrieve your cached object exactly in the instance where you put it!
I will write a MyCache version that will take care of that shortly .. stay tuned