要将操纵memcached的模块插入nginx中,但nginx源码用c写的,编译器也是gcc, 所以为了能顺利通过,使用纯c编写一个libmemcache的客户端
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <libmemcached/memcached.h>
#define DEBUG_READ 1
static memcached_st *memc;
void Init_memcached()
{
memcached_return rc;
memcached_server_st *servers;
//connect multi server
memc = memcached_create(NULL);
servers = memcached_server_list_append(NULL, (char*)"localhost", 11211, &rc);
//servers = memcached_server_list_append(servers, (char*)"localhost", 30000, &rc);
rc = memcached_server_push(memc, servers);
memcached_server_free(servers);
memcached_behavior_set(memc,MEMCACHED_BEHAVIOR_DISTRIBUTION,MEMCACHED_DISTRIBUTION_CONSISTENT);
memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_RETRY_TIMEOUT, 20) ;
// memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_REMOVE_FAILED_SERVERS, 1) ; // 同时设置MEMCACHED_BEHAVIOR_SERVER_FAILURE_LIMIT 和 MEMCACHED_BEHAVIOR_AUTO_EJECT_HOSTS
memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_SERVER_FAILURE_LIMIT, 5) ;
memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_AUTO_EJECT_HOSTS, 1) ;
}
int Insert(const char* key, const char* value,time_t expiration)
{
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;
}
};
const char* Get(const char* key)
{
if (NULL == key)
{
return "no key";
}
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 "no value";
};
int main(int argc, char *argv[])
{
Init_memcached();
const char *mem_key = "/test.html";
const char *mem_value = "what a beautifule day!\r\nYes, it is.";
#if DEBUG_READ
int result = Insert(mem_key,mem_value, 0);
if(result)
{
printf("insert key: %s, value: %s\n", mem_key, mem_value);
}
#endif
const char* get_value = Get(mem_key);
printf("get_value: %s\n", get_value);
//free
if(memc)
{
memcached_free(memc);
}
return 0;
}
编译时候需要链接memcached的动态库, -lmemcached, 所以编译命令为
gcc -lmemcached -g test.c -o test