返回宝典

C/C++ 客户端

上一节 下一节

C/C++语言关于Memcached的客户端比较推荐libmemcached库。


安装 libmemcached

首先,下载libmemcached库,点击这里进行下载;再如下所示解压与安装libmemcached库,将libmemcached.so文件所在目录加入到系统变量LD_LIBRARY_PATH中。(不同操作系统的路径可能不一样,请自行查看自己的安装目录)

$ tar -xvf libmemcached-1.0.18.tar.gz 
$ cd libmemcached-1.0.18 
$ ./configure 
$ sudo make 
$ sudo make install

# 配置path
$ export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH(替换成libmemcached.so文件所在目录)

使用示例

这里是一个简单的示例,以编写mcDemo.cpp为例:

#include<iostream>
#include <string.h>
#include <libmemcached/memcached.h>

using namespace std;

int main(int argc, char *argv[])
{
    memcached_st *client = NULL;
    memcached_return cache_return;
    memcached_server_st *server = NULL;

    client = memcached_create(NULL);
    server = memcached_server_list_append(server, "10.11.8.76", 12007, &cache_return);
    cache_return = memcached_server_push(client, server);

    if(MEMCACHED_SUCCESS != cache_return){
        cout<<"memcached server push failed! cache return:"<<cache_return<<endl;
        return -1;
    }

    string key = "test_key";
    string val = "test_value";
    size_t key_len = key.length();
    size_t val_len = val.length();
    int expiration = 0;
    uint32_t flags = 0;
    cache_return = memcached_set(client, key.c_str(), key_len, val.c_str(), val_len, expiration, flags);

    if(MEMCACHED_SUCCESS === cache_return){
        cout<<"set success"<<endl;
    }else{
        cout<<"set failed! cache return:"<<cache_return<<endl;
    }

    size_t value_length;
    char* getVal = memcached_get(client, key.c_str(), key_len, &value_length, &flags, &cache_return);

    if(MEMCACHED_SUCCESS === cache_return){
        cout<<"get success, value = "<<getVal<<endl;
    }else{
        cout<<"get failed! cache return:"<<cache_return<<endl;
    }

    return 0;
}


然后如下进行编译:

$ g++ -g -Wall -std=c++0x mcDemo.cpp -lmemcached -lpthread -o memcached


运行程序:

$ ./memcached


若成功运行则如下输出:

set success
get success, value = test_value

C/C++ 客户端

上一节 下一节