memcached安装和libmemcached的使用
环境和版本
操作系统:Ubuntu14.04 32bit
libevent版本: 2.0.21
memdatach版本: v1.4.21
libevent安装
#wget http://github.com/downloads/libevent/libevent/libevent-2.0.21-stable.tar.gz #tar -xvzf libevent-2.0.21-stable.tar.gz #cd libevent-2.0.21-stable #./configure -prefix=/usr #make #make install
查看是否安装成功:
#ls /usr/lib/ | grep libevent
memcached安装
#wget wget http://www.memcached.org/files/memcached-1.4.21.tar.gz #tar -xvzf memcached-1.4.21.tar.gz #cd memcached-1.4.21 #./configure -with-libevent=/usr #make #make install
查看是否安装成功:
#ll /usr/local/bin
memcached启动
#/usr/local/bin/memcached -d -u root -m 512 127.0.0.1 -p 11211
查看侦听端口和进程信息:
#netstat -a |grep 11211 #ps -ef | grep memcached
测试memcached
连接memcached最简单的方法是通过telnet。
#telnet 127.0.0.1 11211
查看memcached的状态(telnet下执行):
stats
键值简单的设置、查看和删除(telnet下执行):
set user_id 0 0 5 12345 get user_id delete user_id get user_id
PS:退出telnet,可以键入alt+] q
libmemcached安装
#wget https://launchpad.net/libmemcached/1.0/1.0.18/+download/libmemcached-1.0.18.tar.gz #tar -xvzf libmemcached-1.0.18.tar.gz #cd libmemcached-1.0.18 #./configure #make #make install
查看libmemcached是否安装成功:
#ls /usr/local/lib | grep libmemcached
使用C++通过libmemcached连接memcached#
C++源文件 libmemcachedtest.cpp
1 #include <iostream> 2 #include <string> 3 #include <libmemcached/memcached.h> 4 5 using namespace std; 6 7 int main(int argc, char *argv[]) 8 { 9 //connect server 10 cout << "test start" << endl; 11 memcached_st *memc; 12 memcached_return rc; 13 memcached_server_st *server; 14 uint32_t flags; 15 16 memc = memcached_create(NULL); 17 cout << "append start" << endl; 18 server = memcached_server_list_append(NULL, "localhost", 11211, &rc); 19 if(rc != MEMCACHED_SUCCESS){ 20 cout << "memcached_server_list_append failed. rc=" << rc << endl; 21 return -1; 22 } 23 24 rc = memcached_server_push(memc, server); 25 if(rc != MEMCACHED_SUCCESS){ 26 cout << "memcached_server_push failed. rc=" << rc << endl; 27 memcached_server_free(server); 28 return -2; 29 }; 30 31 memcached_server_list_free(server); 32 33 string key = "key"; 34 string value = "value"; 35 size_t value_length = value.length(); 36 size_t key_length = key.length(); 37 38 //Save data 39 cout << "save data" << endl; 40 rc = memcached_set(memc, key.c_str(), key_length, value.c_str(), value_length, 0, flags); 41 if(rc == MEMCACHED_SUCCESS){ 42 cout << "save data sucessful, key=" << key << ",value=" << value <<endl; 43 }else{ 44 cout << "save data faild, rc=" << rc <<endl