Friday, August 14, 2015

Very Simple Libmemcached Sample Code

Libmemcached documentation can be a bit overwhelming for those new to memcached client library. The sample code below shows a very simple libmemcached usage sample. It assumes that you have libmemcached >= v1.0 in your machine installed. The code comes with no warranty whatsoever, use it a your own risk. Here comes the code:
#include < stdio.h >
#include < stdint.h >
#include <libmemcached-1.0/memcached.h >
#include < stdlib.h >

#define DEFAULT_PORT 7500

int main (int argc, char *argv[])
{
  memcached_return_t rc;
  char * value; 
  char buffer[1024];
  int length= snprintf(buffer, sizeof(buffer), "--server=localhost:%d", DEFAULT_PORT);
  char key[] = "my_key";
  char obj_value[] = "my value";
  size_t obj_val_len;

  memcached_st *memc= memcached(buffer, length);
  if (memc == NULL) {
     printf("Error: Failed to allocate memcached_st object\n");
  }

  rc = memcached_set(memc, key, strlen(key), obj_value, strlen(obj_value) + 1, 0, 0);
  if (rc != MEMCACHED_SUCCESS) {
     printf("Error: Failed to set memcached object value\n");
  }

  value = memcached_get(memc, key, strlen(key), &obj_val_len, 0, &rc);
  if (value == NULL) {
     printf("Error: Failed to read object value\n");
  }
  
  if (MEMCACHED_SUCCESS == rc) {
     printf("Object contents = %s\n", value);
  } else {
     printf("Error: Failed to read object value correctly\n");
  } 

  if (value != NULL) {
     free(value);
  }

  memcached_free(memc);

  return 0;
}
The sample codes simply stores a value ("my value" string) into memcached server running in localhost at port 7500 and read it back to make sure the value stored correctly. This sample code assumes you're running memcached server in your local machine and make it listen at port 7500. This is how I do that:
me@darkstar $ ./memcached -l 127.0.0.1 -p 7500
If you want to change the port, simply change the DEFAULT_PORT definition.

Anyway, the purpose of this post is as a very gentle introduction to libmemcahed. Head over to http://docs.libmemcached.org/index.html for more details.
Post a Comment