For some plugins I am working on for Drizzle, I am using the libmemcached API. However, the C++ interface for libmemcached was quite simple and not really C++ so we have updated it a little bit in the last few months since drizzle is written in C++ and it would be nice to use a more C++-like interface in libmemcached. In this post, I'll show some simple sample usage of the libmemcached C++ interface based on this article about using memcached with Java. Please note that not all this functionality is in the latest stable version of libmemcached but it will likely be in the next release.


I am going to assume that memcached is already installed (see here for a good guide to installing it). To obtain libmemcached, we can either obtain the latest version of the source from launchpad, download an RPM, or download a tarball of the latest stable release and build that. I'm going to go with downloading a tarball since not everyone might have bzr installed. The latest stable release can be obtained from here.
$ cd libmemcached-0.32
$ ./configure
$ make
$ sudo make install
$ sudo ldconfig

Basic Usage

The API is very similar to the C API except more suited to C++. Some simple examples of constructing a memcached client are shown:

There are many more methods available than the 3 listed above but for most simple applications, those 3 should get you pretty far. We still need to add documentation for the C++ interface which should also be included in the next stable release of libmemcached.

MyCache Singleton

As done in the Java article, I create a wrapper around the memcached client as so:

The DeletePtrs class is simply a generic function object that deletes the pointers in an STL container. I use this to delete all the Memcache objects in the vector before it is destroyed to ensure I don't have a memory leak (have a look at item 7 in Meyer's Effective STL for more information).

Sample Usage

Below, we show some samples of using the MyCache singleton. We assume that Product is some class that has been developed elsewhere that we want to cache.

That's about it really. As you can see, the C++ interface has been improved in libmemcached. There is still some more work needed on the C++ interface but I think its starting to look a lot better.

blog comments powered by Disqus


19 September 2009