#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 7500If 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
1 comment:
nice article
Post a Comment