1. 下载hiredis安装包到linux目录/opt;并安装
git clone https://github.com/redis/hiredis.git
cd hiredis
make
sudo make install
注意:安装后有可能共享库不能被正确加载或者系统的搜索路径中没有包含这个库,参考:这个文章
**2. 编写C++代码:**这个其实是上方git下来的源码中的example的改进:由于我的redisserver设置了密码:111111,所以要改进,而且我这里使用的是6381端口,redis服务器在本机
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hiredis/hiredis.h> //头文件此含
#ifdef _MSC_VER
#include <winsock2.h> /* For struct timeval */
#endif
/*这个函数演示如何使用 redisCommandArgv 函数发送命令和参数。这个函数使用 redisCommandArgv 函数执行 Redis 命令 RPUSH,将一系列元素推入列表 argvlist。它演示了如何构建参数数组并传递给 redisCommandArgv。*/
static void example_argv_command(redisContext *c, size_t n) {
char **argv, tmp[42];
size_t *argvlen;
redisReply *reply;
/* We're allocating two additional elements for command and key */
argv = (char **)malloc(sizeof(*argv) * (2 + n));
argvlen = (size_t *)malloc(sizeof(*argvlen) * (2 + n));
/* First the command */
argv[0] = (char*)"RPUSH";
argvlen[0] = sizeof("RPUSH") - 1;
/* Now our key */
argv[1] = (char*)"argvlist";
argvlen[1] = sizeof("argvlist") - 1;
/* Now add the entries we wish to add to the list */
for (size_t i = 2; i < (n + 2); i++) {
argvlen[i] = snprintf(tmp, sizeof(tmp), "argv-element-%zu", i - 2);
argv[i] = strdup(tmp);
}
/* Execute the command using redisCommandArgv. We're sending the arguments with
* two explicit arrays. One for each argument's string, and the other for its
* length. */
reply = (redisReply *)redisCommandArgv(c, n + 2, (const char **)argv, (const size_t *)argvlen);
if (reply == NULL || c->err) {
fprintf(stderr, "Error: Couldn't execute redisCommandArgv\n");
exit(1);
}
if (reply->type == REDIS_REPLY_INTEGER) {
printf("%s reply: %lld\n", argv[0], reply->integer);
}
freeReplyObject(reply);
/* Clean up */
for (size_t i = 2; i < (n + 2); i++) {
free(argv[i]);
}
free(argv);
free(argvlen);
}
int main(int argc, char **argv) {
/*根据命令行参数确定是否使用 Unix 套接字连接或网络套接字连接到 Redis 服务器。
使用 redisConnectWithTimeout 或 redisConnectUnixWithTimeout 函数进行连接,并检查是否成功。*/
unsigned int j, isunix = 0;
redisContext *c;
redisReply *reply;
const char *hostname = (argc > 1) ? argv[1] : "127.0.0.1";
if (argc > 2) {
if (*argv[2] == 'u' || *argv[2] == 'U') {
isunix = 1;
/* in this case, host is the path to the unix socket */
printf("Will connect to unix socket @%s\n", hostname);
}
}
int port = (argc > 2 && !isunix) ? atoi(argv[2]) : 6381;
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
if (isunix) {
c = redisConnectUnixWithTimeout(hostname, timeout);
} else {
c = redisConnectWithTimeout(hostname, port, timeout);
}
if (c == NULL || c->err) {
if (c) {
printf("Connection error: %s\n", c->errstr);
redisFree(c);
} else {
printf("Connection error: can't allocate redis context\n");
}
exit(1);
}
/* 使用 redisCommand 函数发送 AUTH 命令进行认证,并检查认证是否成功。 */
reply = redisCommand(c,"AUTH %s", "111111");
if (reply == NULL || reply->type == REDIS_REPLY_ERROR) {
if (reply) {
printf("AUTH error: %s\n", reply->str);
freeReplyObject(reply);
} else {
printf("AUTH error: no reply\n");
}
redisFree(c);
exit(1);
}
freeReplyObject(reply);
/*发送 PING 命令,并打印返回的结果。 */
reply = redisCommand(c,"PING");
printf("PING: %s\n", reply->str);
freeReplyObject(reply);
/* 通过 SET 命令设置键值,并通过 GET 命令获取键值。 */
reply = redisCommand(c,"SET %s %s", "foo", "hello world");
printf("SET: %s\n", reply->str);
freeReplyObject(reply);
/* Set a key using binary safe API */
reply = redisCommand(c,"SET %b %b", "bar", (size_t) 3, "hello", (size_t) 5);
printf("SET (binary API): %s\n", reply->str);
freeReplyObject(reply);
/* Try a GET and two INCR */
reply = redisCommand(c,"GET foo");
printf("GET foo: %s\n", reply->str);
freeReplyObject(reply);
/* 通过 INCR 命令对计数器进行自增操作。 */
reply = redisCommand(c,"INCR counter");
printf("INCR counter: %lld\n", reply->integer);
freeReplyObject(reply);
reply = redisCommand(c,"INCR counter");
printf("INCR counter: %lld\n", reply->integer);
freeReplyObject(reply);
/* 通过 LPUSH 命令向列表添加元素,并通过 LRANGE 命令获取列表中的所有元素。 */
reply = redisCommand(c,"DEL mylist");
freeReplyObject(reply);
for (j = 0; j < 10; j++) {
char buf[64];
snprintf(buf, 64, "%u", j);
reply = redisCommand(c,"LPUSH mylist element-%s", buf);
freeReplyObject(reply);
}
/* Let's check what we have inside the list */
reply = redisCommand(c,"LRANGE mylist 0 -1");
if (reply->type == REDIS_REPLY_ARRAY) {
for (j = 0; j < reply->elements; j++) {
printf("%u) %s\n", j, reply->element[j]->str);
}
}
freeReplyObject(reply);
/* 调用 example_argv_command 函数,演示如何使用 redisCommandArgv 发送命令。*/
example_argv_command(c, 10);
/* 使用 redisFree 函数断开与 Redis 服务器的连接并释放上下文。 */
redisFree(c);
return 0;
}
3.编译和运行
gcc -o example example1.c -I/usr/local/include/hiredis -L/usr/local/lib -lhiredis
./exmaple
4、运行结果
PING: PONG
SET: OK
SET (binary API): OK
GET foo: hello world
INCR counter: 5
INCR counter: 6
0) element-9
1) element-8
2) element-7
3) element-6
4) element-5
5) element-4
6) element-3
7) element-2
8) element-1
9) element-0
RPUSH reply: 30
总结过程:
- 创建 Redis 连接
使用 redisConnect(连接到 TCP 套接字) 或 redisConnectUnix(连接到 Unix 套接字) 函数连接到 Redis 服务器。你需要指定 Redis 服务器的主机名和端口(或 Unix 套接字路径)。 - 检查连接是否成功,并处理可能的错误:
- 如果 Redis 服务器启用了密码保护,使用 AUTH 命令进行身份验证:
- 发送 Redis 命令:使用 redisCommand 发送 Redis 命令并获取响应。redisCommand 函数会阻塞直到命令执行完成并返回结果。
- 处理响应:根据响应的类型处理返回结果。Redis 回复类型包括字符串、整数、数组等。
- 断开连接
如果你需要更复杂的命令构建,可以使用 redisCommandArgv 来发送命令。它允许你用数组形式传递参数,适用于动态构建命令。
还可以另外参考:本文章和此片文章中引用的文章