Connecting to Memcache using the libmemcached C library
My job description has changed: I am going to need to learn the basics of C/C++. As part of the requirements for a specific ticket I needed to retrieve data from Memcache. I just can't believe how difficult it is to achieve this task compared to PHP!
The following code works. It relies on the libmemcached C library.
#include <cstdlib>
#include <iostream>
#include <string>
#include <libmemcached/memcached.h>
int main(int argc, char** argv) {
// Declare and instantiate hostname of the server
std::string servername = "127.0.0.1";
// Declare and instantiate cacheKey string
std::string cacheKey = "comScoreData";
// Declare error code variable
memcached_return_t rc;
// Declare length of data that will be returned by memcached
size_t valueLength;
// Declare and instantiate flags to pass to memcached
uint32_t flags = 0;
// Declare and instantiate an instance of memcached
memcached_st* memc= ::memcached_create(NULL);
// Appends server connection details to collection
memcached_server_st *servers = memcached_server_list_append(NULL, servername.c_str(), 11211, &rc);
// Add server connection details and tell memcached to connect to it
rc = memcached_server_push(memc, servers);
/* Retrieve data from memcached given:
* memcached instance, cacheId, length of cacheId,
* reference to length of expected data, reference to flags,
* reference to error code */
char* data = memcached_get(memc, cacheKey.data(), cacheKey.length(), &valueLength, &flags, &rc);
// Free memory allocated for memcached
memcached_free(memc);
// Print out byte by byte
for (int i = 0; i < valueLength; ++i) {
std::cout << static_cast<int>(data[i]) << " ";
}
// Print end of line
std::cout << std::endl;
// Success
return 0;
}
Post new comment