最近要用C++开发项目需要操作memcached,查找到libmemcached是专门为C/C++提供的memcached客户端决定用它。
在Ubuntu上安装memcached和libmemcached
1. 在命令行下: wget https://launchpad.net/libmemcached/1.0/1.0.7/+download/libmemcached-1.0.7.tar.gz 下载文件。
2. 输入:sudo apt-get install libevent-dev 安装libevent-dev (据说这个很重要,不然libmemcached就不能运行,最好安装)
3. 解压缩下载文件:sudu tar -zxvf libmemcached-1.0.7.tar.gz
4. 编译: ./configure
5. 输入:make
这里很可能会出下面错误:
libmemcached/backtrace.cc: In function 'void custom_backtrace()':
libmemcached/backtrace.cc:57:6: sorry, unimplemented: Graphite loop optimizations can only be used if the libcloog-ppl0 package is installed
解决办法是修改Makefile,查找并去掉 floop-parallelize-all(应该有两处需要去掉),看了网上资料说是去掉后表示不使用Graphite loop 优化。
成功编译。
6. 安装:make install
7. 编写文件 MemCachedClient.h 输入下面内容:
#ifndef MEMCACHEDCLIENT
#define MEMCACHEDCLIENT
#include <libmemcached/memcached.h>
#include<iostream>
#include<string>
#include<time.h>
using std::string;
using std::cout;
using std::endl;
class MemCachedClient
{
public:
~MemCachedClient()
{
memcached_free(memc);
};
MemCachedClient()
{
memcached_return rc;
memcached_server_st *server = NULL;
memc = memcached_create(NULL);
server =memcached_server_list_append(server, "192.168.45.144", 11211, &rc);
rc=memcached_server_push(memc,server);
if (MEMCACHED_SUCCESS != rc) {
cout <<"memcached_server_push failed! rc: " << rc << endl;
}
memcached_server_list_free(server);
};
int Insert(const char* key, const char* value,time_t expiration = 3)
{
if (NULL == key || NULL == value)
{
return -1;
}
uint32_t flags = 0;
memcached_return rc;
rc = memcached_set(memc, key, strlen(key),value, strlen(value), expiration, flags);
// insert ok
if (MEMCACHED_SUCCESS == rc)
{
return 1;
}
else
{
return 0;
}
};
string Get(const char* key)
{
if (NULL == key)
{
return "";
}
uint32_t flags = 0;
memcached_return rc;
size_t value_length;
char* value = memcached_get(memc, key, strlen(key), &value_length, &flags, &rc);