The C++ redis client based on acl is easy to use, which supports cluster redis and single redis in multi-threads envirenment. Below is a simple exmple:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <vector>
#include "acl_cpp/lib_acl.hpp"
static int __max_conns = 100;
static void test_redis_string(acl::redis& cmd, const char* key)
{
acl::string val("test_value");
// call redis-server: SET key value
if (cmd.set(key, val.c_str()) == false)
{
printf("redis set error: %s\r\n", cmd.result_error());
return;
}
// clear the string buf space
val.clear();
// call redis-server: GET key
if (cmd.get(key, val) == false)
printf("get key error: %s\r\n", cmd.result_error());
}
static void test_redis_hash(acl::redis& cmd, const char* key)
{
std::map<acl::string, acl::string> fields;
fields["name1"] = "value1";
fields["name2"] = "value2";
fields["name3"] = "value3";
// HMSET key field value ...
if (cmd.hmset(key, fileds) == false)
{
printf("hmset failed: %s\r\n", cmd.result_error());
return;
}
const char* names[] = { "name1", "name2", "name3" };
size_t argc = 3;
std::vector<acl::string> values;
// HMGET key filed ...
if (cmd.hmget(key, names, argc, &values) == false)
{
printf("hmget failed: %s\r\n", cmd.result_error());
return;
}
printf("%s: %s, %s: %s, %s: %s\r\n",
names[0], values[0].c_str(),
names[1], values[1].c_str(),
names[2], values[2].c_str());
}
static void test_redis_key(acl::redis& cmd, const char* key)
{
if (cmd.exists(key) == false)
printf("key not exists\r\n");
else
printf("key exists\r\n");
}
// run in one thread
static void* thread_main(void* arg)
{
acl::redis_client_cluster* cluster = (acl::redis_client_cluster*) arg;
acl::redis cmd;
cmd.set_cluster(cluster, __max_conns);
const char* key;
for (int i = 0; i < 100000; i++)
{
key = "string_key";
test_redis_string(cmd, key);
test_redis_key(cmd, key);
key = "hash_key";
test_redis_hash(cmd, key);
test_redis_key(cmd, key);
// reset the redis command to free some memory
cmd.clear();
}
return NULL;
}
int main(void)
{
const char* redis_addr = "
127.0.0.1:6379";
int conn_timeout = 10, rw_timeout = 10;
// declare redis cluster ojbect
acl::redis_client_cluster cluster;
cluster.set(redis_addr, __max_conns);
pthread_attr_t attr;
pthread_attr_init(&attr);
// create first thread
pthread_t id1;
pthread_create(&id1, &attr, thread_main, &cluster);
// create second thread
pthread_t id2;
pthread_create(&id2, &attr, thread_main, &cluster);
pthread_join(&id1, NULL);
pthread_join(&id2, NULL);
return 0;
}
zsx
在 2015年4月2日星期四 UTC+8下午10:44:27,ShuXin Zheng写道: