最近要用C++开发项目需要操作memcached,查找到libmemcached是专门为C/C++提供的memcached客户端决定用它。
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);
// get ok
if(rc == MEMCACHED_SUCCESS)
{
return value;
}
return “”;
};
private:
memcached_st* memc;
};
#endif
再编写 test.cc 文件
#include<iostream>
#include“MemCachedClient.h“
using std::cout;
using std::endl;
int main()
{
MemCachedClient mc;
mc.Insert(“kingcat“,”value123”); cout << mc.Get( “ kingcat “) << endl;
return 1;
};
8. 用g++编译: g++ test.cc -o test -lmemcached (一定别把库链接忘了否则编译不通过)
9. 执行./test
执行时会报错:libmemcached.so.10: cannot open shared object file: No such file or director
原因是 libmemcached.so.10 被安装到了 /usr/local/lib下,而共享库默认位置是 /usr/lib 网上说可以把目录 /usr/local/lib 设置到环境变量,但我设置完后不起作用。
于是用建立一个链接: ln /usr/local/lib/libmemcached.so.10 /usr/lib/libmemcached.so.10
重新执行,顺利通过!