目录

  • Hiredis
    • 1. Hiredis简介
    • IMPORTANT: Breaking changes from `0.14.1` -> `1.0.0` (一些更改)
    • 2. Synchronous API(同步API)
      • 2.1 Connecting(连接)
      • 2.2 Sending commands(发送命令)
      • 2.3 Using replies(使用回复)
      • 2.4 RESP2
      • 2.5 RESP3
      • 2.6 Cleaning up(清理)
      • 2.7 Sending commands (cont'd)(发送命令)(二进制安全)
      • 2.8 Pipelining 流水线
      • 2.9 Errors错误
    • 3. Asynchronous API(异步API)
      • 3.1 Connecting(连接)
      • 3.2 Sending commands and their callbacks(发送命令和它们的回调)
      • 3.3 Disconnecting(断开)
      • 3.4 Hooking it up to event library X(将其连接到事件库X)
    • 4 Reply parsing API(回复解析API)
      • 4.1 Usage(使用)
      • 4.2 Customizing replies(定制答道)
      • 4.3 Reader max buffer(Reader的最大缓冲区)
      • 4.4 Reader max array elements(reader数组元素的最大个数)
    • 5 SSL/TLS Support
      • 5.1 Building
      • 5.2 Using it
        • 5.2.1 Hiredis OpenSSL Wrappers
    • 6 RESP3 PUSH replies
      • 6.1 Default behavior(默认的行为)
      • 6.2 Custom PUSH handler prototypes(自定义PUSH处理程序原型)
        • 6.2.1 redisContext
        • 6.2.2 redisAsyncContext
      • 6.3 Installing a custom handler(安装自定义处理程序)
      • 6.4 Specifying no handler(没有指定处理程序)
    • hiredis官方例程
      • 1. example.c
      • 2. example-libevent.c
      • 3. example-ssl.c
  • 但是链接openssl/ssl.h时报错!???
  • 编译报错!待解决!有时间解决一下
      • 4. example-libevent-ssl.c
      • 5. example-push.c
    • MyDemo
      • hiredis_hash_test.c


官网:https://github.com/redis/hiredis
https://redislabs.com/lp/hiredis/
https://github.com/redis/hiredis/releases



Hiredis

1. Hiredis简介

Hiredis是Redis数据库的一个极简C客户端库。

它是极简主义的,因为它只增加了对协议的最小支持,但同时它使用了一个高级的类似printf的API。

除了支持发送命令和接收应答之外,它还附带了一个与I/O层分离的应答解析器。它是一个流解析器,设计为易于重用,例如,它可以用于更高级别的语言绑定,以实现高效的应答解析。

Hiredis只支持二进制安全的Redis协议,所以你可以使用它与任何版本的Redis >= 1.2.0。

这个库附带了多个api。有同步API、异步API和应答解析API。

IMPORTANT: Breaking changes from 0.14.1 -> 1.0.0 (一些更改)

  • redisContext has two additional members (free_privdata, and privctx).
  • redisOptions.timeout has been renamed to redisOptions.connect_timeout, and we’ve added redisOptions.command_timeout.
  • redisReplyObjectFunctions.createArray now takes size_t instead of int for its length parameter.

2. Synchronous API(同步API)

要使用同步API,只需要引入几个函数调用:

redisContext *redisConnect(const char *ip, int port);
void *redisCommand(redisContext *c, const char *format, ...);
void freeReplyObject(void *reply);

2.1 Connecting(连接)

redisConnect函数用于创建所谓的redisContext。
Context(上下文)是Hiredis保存连接状态的地方。

redisContext结构
1 有一个整数err字段,当连接处于错误状态时,这个字段是非零的。
2 errstr字段将包含一个包含错误描述的字符串。
3 关于错误的更多信息可以在Errors一节(见下文)中找到。
4 在尝试使用redisConnect连接Redis,你应该检查err字段,看看是否建立连接成功:

redisContext *c = redisConnect("127.0.0.1", 6379);
if (c == NULL || c->err) {if (c) {printf("Error: %s\n", c->errstr);// handle error} else {printf("Can't allocate redis context\n");}
}

注意:redisContext不是线程安全的。

2.2 Sending commands(发送命令)

有几种方法可以向Redis发出命令。首先要介绍的是redisCommand。该函数采用类似于printf的格式。最简单的形式是这样使用的:

reply = redisCommand(context, "SET foo bar");

说明符%s在命令中插入一个字符串,并使用strlen来确定字符串的长度:

reply = redisCommand(context, "SET foo %s", value);

当你需要在命令中传递二进制安全字符串时,可以使用%b说明符。与指向字符串的指针一起,它需要string对象的size_t长度参数:

reply = redisCommand(context, "SET foo %b", value, (size_t) valuelen);

在内部,Hiredis以不同的参数拆分命令,并将其转换为与Redis通信的协议。一个或多个空格分隔参数,所以你可以在参数的任何位置使用说明符:

reply = redisCommand(context, "SET key:%s %s", myid, value);

2.3 Using replies(使用回复)

当命令成功执行时,redisCommand的返回值保存一个应答。
当错误发生时,返回值为NULL,并且上下文中的err字段将被设置(参见Errors部分)。
一旦返回错误,就不能重用上下文,您应该建立一个新的连接。

redisCommand的标准应答类型为redisReply。redisReply中的type字段应该用来测试收到了什么类型的回复:

2.4 RESP2

  • REDIS_REPLY_STATUS:
    The command replied with a status reply. (返回应答状态)
    状态字符串可以使用reply->str访问。
    该字符串的长度可以通过reply->len访问。

  • REDIS_REPLY_ERROR:
    The command replied with an error.(返回一个错误)。
    可以访问与REDIS_REPLY_STATUS相同的错误字符串(reply->str) 查看错误描述。

  • REDIS_REPLY_INTEGER:
    The command replied with an integer. (返回一个整数)
    该整数值可以通过long long类型的reply->integer字段访问。

  • REDIS_REPLY_NIL:
    The command replied with a nil object. (返回一个nil对象)。
    没有数据可访问。

  • REDIS_REPLY_STRING:
    A bulk (string) reply.(批量(字符串)) 。
    返回的值可以通过reply->str访问。该字符串的长度可以通过reply->len访问。

  • REDIS_REPLY_ARRAY:
    A multi bulk reply. (一个多批量回复(其实就是数组))。
    数组的元素个数存储在reply->elements中。
    每个元素也是一个redisReply对象,可以通过reply->element[…index…]访问数组中的某个元素。
    Redis可能会用嵌套数组来回复,这是完全支持的。

2.5 RESP3

Hiredis还支持如下所示的每一种新的RESP3数据类型。有关协议的更多信息,请参见RESP3规范。

  • REDIS_REPLY_DOUBLE:
    The command replied with a double-precision floating point number. (返回一个双精度浮点数)。
    该值存储在str成员中 存储为字符串,可以使用strtod或类似的方法进行转换。

  • REDIS_REPLY_BOOL:
    A boolean true/false reply. (返回一个bool值)。
    该值存储在integer成员中,值为0或1。

  • REDIS_REPLY_MAP:
    An array with the added invariant that there will always be an even number of elements. (添加元素个数始终为偶数的不变式的数组)。
    除了前面提到的不变式外,这个映射在函数上等价于REDIS_REPLY_ARRAY。

  • REDIS_REPLY_SET:
    An array response where each entry is unique. 一个数组响应,其中每个条目都是唯一的。
    与映射类型一样,除了没有重复的值之外,数据与数组响应是相同的。

  • REDIS_REPLY_PUSH:
    An array that can be generated spontaneously by Redis. 一个可以由Redis自动生成的数组。
    此数组响应将始终包含至少两个子元素。第一个包含推送消息的类型(例如message或invalidate),第二个是包含推送有效负载本身的子数组。

  • REDIS_REPLY_ATTR:
    从Redis 6.0.6开始,这个回复类型在Redis中不被使用

  • REDIS_REPLY_BIGNUM:
    A string representing an arbitrarily large signed or unsigned integer value.表示任意大的有符号或无符号整数值的字符串。
    该数字将在redisReply的str成员中被编码为字符串。

  • REDIS_REPLY_VERB:
    A verbatim string, intended to be presented to the user without modification. 一种一字不差的字符串,不经修改就呈现给用户。
    字符串有效载荷存储在str成员中,类型数据存储在vtype成员中(例如txt是原始文本,md是markdown)。

回复应该使用freeReplyObject()函数释放。
注意,这个函数将负责释放包含在数组和嵌套数组中的子应答对象,因此用户不需要释放子应答(这实际上是有害的,将破坏内存)。

重要提示:
当使用异步API时,hiredis(1.0.0)的当前版本会释放应答。
这意味着当你使用这个API时,你不应该调用freeReplyObject。
回调返回后,应答被hiredis清理。
我们可能会引入一个标志,以便在库的未来版本中对此进行配置。

2.6 Cleaning up(清理)

要断开和释放上下文,可以使用以下函数:

void redisFree(redisContext *c);

这个函数立即关闭套接字,然后释放在创建上下文时完成的分配。

2.7 Sending commands (cont’d)(发送命令)(二进制安全)

与redisCommand一样,可以使用redisCommandArgv函数发出命令。它的原型如下:

void *redisCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen);

接受的参数个数为:argc;
各个参数(每个参数是一个字符串):字符串数组argv(这是一个:元素类型为char*的数组);
各个参数的长度:argvlen(这是一个:元素类型为size_t的数组)。

为方便起见,argvlen可以设置为NULL,并且函数将在每个参数上使用strlen(3)来确定其长度。
显然,当任何参数都需要二进制安全时,应该在数组argvlen中提供每个参数的长度。

返回值具有与redisCommand相同的语义。

2.8 Pipelining 流水线

为了解释Hiredis如何在阻塞连接中支持管道,需要了解内部执行流。

当redisCommand家族中的任何一个函数被调用时,Hiredis首先根据Redis协议格式化命令。格式化的命令然后放入上下文的输出缓冲区。这个输出缓冲区是动态的,因此它可以容纳任意数量的命令。在将命令放入输出缓冲区之后,将调用redisGetReply。该函数有以下两条执行路径:

  1. 输入缓冲区非空:
    尝试解析来自输入缓冲区的单个响应并返回它
    如果没有可以解析的答复,继续2
  2. 输入缓冲区为空:
    将整个输出缓冲区写入套接字
    从套接字读取,直到可以解析单个应答

函数redisGetReply作为Hiredis API的一部分,可以在套接字上期待应答时使用。
对于管道命令,唯一需要做的事情是填充输出缓冲区。
由于这个原因,除了不返回应答外,可以使用两个与redisCommand家族相同的命令:

void redisAppendCommand(redisContext *c, const char *format, ...);
void redisAppendCommandArgv(redisContext *c, int argc, const char **argv, const size_t *argvlen);

在调用任意一个函数一次或多次后,可以使用redisGetReply来接收后续的响应。
该函数的返回值是REDIS_OK或REDIS_ERR,后者表示在读取应答时发生了错误。
与其他命令一样,上下文中的err字段可以用来找出导致此错误的原因。

下面的例子展示了一个简单的管道(导致只有一个write(2)调用和一个read(2)调用):

redisReply *reply;
redisAppendCommand(context,"SET foo bar");
redisAppendCommand(context,"GET foo");
redisGetReply(context,(void *)&reply); // reply for SET
freeReplyObject(reply);
redisGetReply(context,(void *)&reply); // reply for GET
freeReplyObject(reply);

这个API也可以用来实现阻塞订阅器:

reply = redisCommand(context,"SUBSCRIBE foo");
freeReplyObject(reply);
while(redisGetReply(context,(void *)&reply) == REDIS_OK) {// consume messagefreeReplyObject(reply);
}

2.9 Errors错误

当函数调用不成功时,根据函数返回NULL或REDIS_ERR。上下文中的err字段将是非零的,并设置为以下常量之一:

REDIS_ERR_IO:在创建连接时出现了一个I/O错误,试图写到套接字或从套接字读取。如果在应用程序中包含了errno.h,则可以使用全局errno变量来找出问题所在。

REDIS_ERR_EOF:服务器关闭连接,导致一个空读。

REDIS_ERR_PROTOCOL:解析协议时出现错误。

REDIS_ERR_OTHER:任何其他错误。目前,它只在指定的主机名无法解析时使用。

在每种情况下,上下文中的errstr字段都将被设置为保存错误的字符串表示形式。

3. Asynchronous API(异步API)

Hiredis提供了一个异步API,可以轻松地与任何事件库一起工作。例如:Hiredis与libev和libevent捆绑使用。

3.1 Connecting(连接)

函数redisAsyncConnect可以用来建立一个非阻塞连接到Redis。
它返回一个指向新创建的redisAsyncContext结构体的指针。
创建后应检查err字段,以查看是否存在创建连接的错误。
因为将要创建的连接是非阻塞的,所以如果指定的主机和端口能够接受连接,内核就不能立即返回。

注意:redisAsyncContext不是线程安全的。

redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);
if (c->err) {printf("Error: %s\n", c->errstr);// handle error
}

异步上下文可以保存一个断开回调函数,当连接断开时(由于一个错误或每个用户请求)调用该函数。这个函数应该有以下的原型:

void(const redisAsyncContext *c, int status);

在断开连接时,当用户发起断开连接时,status参数被设置为REDIS_OK,或者当由错误导致断开连接时设置为REDIS_ERR。当它是REDIS_ERR时,可以访问上下文中的err字段来找出错误的原因。

在断开回调触发后,context对象总是被释放。当需要重新连接时,断开回调是一个很好的选择。

每个上下文只能设置一次断开回调。对于后续调用,它将返回REDIS_ERR。设置断开回调函数的原型如下:

int redisAsyncSetDisconnectCallback(redisAsyncContext *ac, redisDisconnectCallback *fn);

ac->data可以用于将用户数据传递给这个回调函数,对于redisConnectCallback也可以这样做。

3.2 Sending commands and their callbacks(发送命令和它们的回调)

在异步上下文中,由于事件循环的性质,命令是自动流水线的。
因此,与同步API不同,发送命令的方式只有一种。
因为命令是异步发送到Redis的,发出命令需要一个回调函数,当收到回复时调用。回复回调应该有以下原型:

void(redisAsyncContext *c, void *reply, void *privdata);

privdata参数可用于将任意数据从命令最初排队等待执行的点发送到回调函数。

在异步上下文中,可以使用以下函数发出命令:

int redisAsyncCommand(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata,const char *format, ...);
int redisAsyncCommandArgv(redisAsyncContext *ac, redisCallbackFn *fn, void *privdata,int argc, const char **argv, const size_t *argvlen);

这两个函数的工作方式都类似于它们的阻塞对应函数。
当命令成功添加到输出缓冲区时,返回值为REDIS_OK,否则返回值为REDIS_ERR。
示例:当根据用户请求断开连接时,不可能向输出缓冲区添加新命令,并且在调用redisAsyncCommand家族时返回REDIS_ERR。

如果读取带有空回调函数的命令的应答,则会立即释放它。
当命令的回调非空时,内存在回调之后立即被释放:应答仅在回调的持续时间内有效。

当上下文遇到错误时,所有挂起的回调都将以空应答调用。

3.3 Disconnecting(断开)

可以使用以下方式终止异步连接:

void redisAsyncDisconnect(redisAsyncContext *ac);

当调用此函数时,连接不会立即终止。相反,新的命令将不再被接受,并且只有当所有挂起的命令都已写入套接字,它们各自的响应已经被读取,它们各自的回调已经被执行时,连接才会终止。在此之后,断开连接回调函数将以REDIS_OK状态执行,上下文对象将被释放。

3.4 Hooking it up to event library X(将其连接到事件库X)

在创建上下文对象之后,需要在其上设置一些钩子。有关绑定到libev和libevent的信息,请参阅适adapters/目录。

4 Reply parsing API(回复解析API)

Hiredis附带了一个应答解析API,这使得编写更高级别的语言绑定变得很容易。

reply解析API由以下函数组成:

redisReader *redisReaderCreate(void);
void redisReaderFree(redisReader *reader);
int redisReaderFeed(redisReader *reader, const char *buf, size_t len);
int redisReaderGetReply(redisReader *reader, void **reply);

当hiredis创建一个普通的Redis上下文时,同样的一组函数被hiredis内部使用,上面的API只是将它暴露给用户直接使用。

4.1 Usage(使用)

redisReaderCreate()函数创建一个redisReader结构体,该结构体为协议解析器保存一个带有未解析数据和状态的缓冲区。

传入的数据——很可能来自套接字——可以使用redisReaderFeed()放置在redisReader的内部缓冲区中。
redisReaderFeed()这个函数将复制buf所指向的len字节的缓冲区。
当调用redisReaderGetReply()时,将解析该数据。
这个函数通过void **reply返回一个整数状态和一个reply对象(如上所述)。返回的状态可以是REDIS_OK或REDIS_ERR,后者表示出了问题(协议错误或内存不足错误)。

解析器将多批量有效负载的嵌套级别限制为7。如果多块嵌套级别高于此级别,解析器将返回一个错误。

4.2 Customizing replies(定制答道)

函数’ redisReaderGetReply() ‘创建’ redisReply ‘,并使函数参数’ reply ‘指向创建的变量’ redisReply '。

例如,如果响应类型为’ REDIS_REPLY_STATUS ‘,那么’ redisReply ‘的’ str '字段将保持状态为普通的C字符串。

但是,可以通过在’ redisReader ‘结构上设置’ fn ‘字段来定制负责创建’ redisReply ‘实例的函数。这应该在创建’ redisReader '后立即完成。

例如, hiredis-rb
使用自定义应答对象函数创建Ruby对象。

4.3 Reader max buffer(Reader的最大缓冲区)

无论是直接使用Reader API还是通过一个普通的Redis上下文间接使用它,redisReader结构都使用一个缓冲区来积累来自服务器的数据。为了避免在未使用的缓冲区中浪费内存,通常这个缓冲区在它为空且大于16 KiB时被销毁

然而,当使用非常大的有效负载时,破坏缓冲区可能会大大降低性能,因此可以修改空闲缓冲区的最大大小,将reader结构体的maxbuf字段的值更改为所需的值。0这个特殊值意味着空闲缓冲区没有最大值,因此该缓冲区永远不会被释放。

例如,如果你有一个普通的Redis上下文,你可以设置最大空闲缓冲区为零(无限制),只需:

context->reader->maxbuf = 0;

这样做只是为了在使用大负载时最大化性能。
为了防止分配无用的内存,上下文应该尽快重新设置为REDIS_READER_MAX_BUF。

4.4 Reader max array elements(reader数组元素的最大个数)

默认情况下,hiredis应答解析器将多块元素的最大数目设置为2^32 - 1或4,294,967,295个条目。如果你需要处理多块的回复,你可以把值设置得更高或为0,这意味着无限:

context->reader->maxelements = 0;

5 SSL/TLS Support

5.1 Building

默认情况下不支持SSL/TLS,需要一个明确的标志:
安装hiredis时,make时要加参数,如下:

make USE_SSL=1

这需要OpenSSL开发包(例如,包括头文件)可用。

When enabled, SSL/TLS支持libhiredis_ssl.a和libhiredis_ssl.so静态/动态库。这使原始库不受影响,因此不会引入额外的依赖项。

5.2 Using it

首先,你需要确保包含SSL头文件:

#include "hiredis.h"
#include "hiredis_ssl.h"

除了libhiredis之外,还需要链接到libhiredis_ssl,并添加-lssl -lcrypto以满足其依赖关系。
Hiredis在其正常的redisContext或redisAsyncContext之上实现了SSL/TLS,所以你需要首先建立一个连接,然后发起SSL/TLS握手。

5.2.1 Hiredis OpenSSL Wrappers

在Hiredis可以协商SSL/TLS连接之前,有必要初始化OpenSSL并创建上下文。你可以通过两种方式做到这一点:

  1. 直接使用OpenSSL API初始化库的全局上下文,并创建SSL_CTX *和SSL *上下文。使用SSL *对象,您可以调用redisInitiateSSL()。
  2. 使用一组hiredis提供的围绕OpenSSL的包装器,创建一个redisSSLContext对象来保存配置,并使用redisInitiateSSLWithContext()来初始化SSL/TLS握手。
/* An Hiredis SSL context. It holds SSL configuration and can be reused across* many contexts.*/
redisSSLContext *ssl_context;/* An error variable to indicate what went wrong, if the context fails to* initialize.*/
redisSSLContextError ssl_error;/* Initialize global OpenSSL state.** You should call this only once when your app initializes, and only if* you don't explicitly or implicitly initialize OpenSSL it elsewhere.*/
redisInitOpenSSL();/* Create SSL context */
ssl_context = redisCreateSSLContext("cacertbundle.crt",     /* File name of trusted CA/ca bundle file, optional */"/path/to/certs",       /* Path of trusted certificates, optional */"client_cert.pem",      /* File name of client certificate file, optional */"client_key.pem",       /* File name of client private key, optional */"redis.mydomain.com",   /* Server name to request (SNI), optional */&ssl_error);if(ssl_context == NULL || ssl_error != 0) {/* Handle error and abort... *//* e.g. printf("SSL error: %s\n", (ssl_error != 0) ? redisSSLContextGetError(ssl_error) : "Unknown error");// Abort*/
}/* Create Redis context and establish connection */
c = redisConnect("localhost", 6443);
if (c == NULL || c->err) {/* Handle error and abort... */
}/* Negotiate SSL/TLS */
if (redisInitiateSSLWithContext(c, ssl_context) != REDIS_OK) {/* Handle error, in c->err / c->errstr */
}

6 RESP3 PUSH replies

Redis 6.0引入了PUSH replies,回复类型为>。这些消息是自发生成的,可以在任何时候到达,因此必须使用回调来处理。

6.1 Default behavior(默认的行为)

默认情况下,Hiredis会在redisContext和redisAsyncContext上安装处理程序,这将拦截并释放检测到的任何推送响应。这意味着在升级到Redis 6和切换到RESP3后,现有的代码将照常工作。

6.2 Custom PUSH handler prototypes(自定义PUSH处理程序原型)

回调原型在’ redisContext ‘和’ redisAsyncContext '之间有所不同。

6.2.1 redisContext

void my_push_handler(void *privdata, void *reply) {/* Handle the reply *//* Note: We need to free the reply in our custom handler forblocking contexts.  This lets us keep the reply ifwe want. */freeReplyObject(reply);
}

6.2.2 redisAsyncContext

void my_async_push_handler(redisAsyncContext *ac, void *reply) {/* Handle the reply *//* Note:  Because async hiredis always frees replies, you shouldnot call freeReplyObject in an async push callback. */
}

6.3 Installing a custom handler(安装自定义处理程序)

有两种方法可以设置自己的PUSH handlers。

  1. 在redisOptions结构体中设置push_cb或async_push_cb,并使用redisConnectWithOptions或redisAsyncConnectWithOptions连接。
redisOptions = {0};
REDIS_OPTIONS_SET_TCP(&options, "127.0.0.1", 6379);
options->push_cb = my_push_handler;
redisContext *context = redisConnectWithOptions(&options);
  1. 在连接的上下文上调用redisSetPushCallback或redisAsyncSetPushCallback。
redisContext *context = redisConnect("127.0.0.1", 6379);
redisSetPushCallback(context, my_push_handler);

注意,redisSetPushCallback和redisAsyncSetPushCallback都返回任何当前配置的处理程序,使它很容易覆盖,然后返回到旧的值。

6.4 Specifying no handler(没有指定处理程序)

如果你有一个独特的用例,你不希望hiredis自动拦截和自由推送回复,你将想要配置任何处理程序。这可以通过两种方式实现。

  1. 在redisOptions中设置REDIS_OPT_NO_PUSH_AUTOFREE标志,并保留回调函数指针为空。
redisOptions = {0};
REDIS_OPTIONS_SET_TCP(&options, "127.0.0.1", 6379);
options->options |= REDIS_OPT_NO_PUSH_AUTOFREE;
redisContext *context = redisConnectWithOptions(&options);
  1. 一旦连接,用NULL调用redisSetPushCallback。
redisContext *context = redisConnect("127.0.0.1", 6379);
redisSetPushCallback(context, NULL);

注意:在没有配置处理程序的情况下,对redisCommand的调用可能会生成多个应答,所以这个策略只适用于存在某种blockingredisGetReply()循环(例如监视或订阅工作负载)的情况。

hiredis官方例程

1. example.c

主要使用了redisConnectWithTimeout()   建立连接redisCommand()              发送redis命令freeReplyObject()          释放每一次的replyredisFree()                  断开连接并释放redisContext
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hiredis/hiredis.h>// /usr/local/include/hiredis/hiredis.h#ifdef _MSC_VER
#include <winsock2.h> /* For struct timeval */
#endifint main(int argc, char **argv)
{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) ? atoi(argv[2]) : 6379;struct timeval timeout = {1, 500000}; // 1.5 secondsif (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);}/* PING server */reply = redisCommand(c, "PING");printf("PING: %s\n", reply->str);freeReplyObject(reply);/* Set a key */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);reply = redisCommand(c, "INCR counter");printf("INCR counter: %lld\n", reply->integer);freeReplyObject(reply);/* again ... */reply = redisCommand(c, "INCR counter");printf("INCR counter: %lld\n", reply->integer);freeReplyObject(reply);/* Create a list of numbers, from 0 to 9 */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);/* Disconnects and frees the context */redisFree(c);return 0;
}
[root@lwh testcpp]# gcc example.c -o out -lhiredis
[root@lwh testcpp]# ./out
PING: PONG
SET: OK
SET (binary API): OK
GET foo: hello world
INCR counter: 1
INCR counter: 2
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
[root@lwh testcpp]#

2. example-libevent.c

主要使用了event_base_new()                创建libevent的事件处理框架实例event_baseredisAsyncConnectWithOptions() 建立连接redisLibeventAttach()           把context添加到event_base上redisAsyncSetConnectCallback()    设置建立连接后的回调redisAsyncSetDisconnectCallback()设置断开连接后的回调redisAsyncCommand()                发送redis命令(可以设置回调函数!!!)event_base_dispatch()            libevent开始事件循环
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>#include <hiredis/hiredis.h> // /usr/local/include/hiredis/hiredis.h
#include <hiredis/async.h>
#include <hiredis/adapters/libevent.h>void getCallback(redisAsyncContext *c, void *r, void *privdata)
{redisReply *reply = r;if (reply == NULL){if (c->errstr){printf("errstr: %s\n", c->errstr);}return;}printf("argv[%s]: %s\n", (char *)privdata, reply->str);/* Disconnect after receiving the reply to GET */redisAsyncDisconnect(c);// 断开连接
}void connectCallback(const redisAsyncContext *c, int status)
{if (status != REDIS_OK){printf("Error: %s\n", c->errstr);return;}printf("Connected...\n");
}void disconnectCallback(const redisAsyncContext *c, int status)
{if (status != REDIS_OK){printf("Error: %s\n", c->errstr);return;}printf("Disconnected...\n");
}int main(int argc, char **argv)
{#ifndef _WIN32signal(SIGPIPE, SIG_IGN);
#endifstruct event_base *base = event_base_new();redisOptions options = {0};REDIS_OPTIONS_SET_TCP(&options, "127.0.0.1", 6379);struct timeval tv = {0};tv.tv_sec = 1;options.timeout = &tv;//options.connect_timeout = &tv;//已经更改redisAsyncContext *c = redisAsyncConnectWithOptions(&options);if (c->err){/* Let *c leak for now... */printf("Error: %s\n", c->errstr);return 1;}redisLibeventAttach(c, base);redisAsyncSetConnectCallback(c, connectCallback);redisAsyncSetDisconnectCallback(c, disconnectCallback);redisAsyncCommand(c, NULL, NULL, "SET key %b", argv[argc - 1], strlen(argv[argc - 1]));redisAsyncCommand(c, getCallback, (char *)"end-1", "GET key");event_base_dispatch(base);return 0;
}
[root@lwh testcpp]# gcc example.c -o out -lhiredis -levent
[root@lwh testcpp]# ./out HelloWorld
Connected...
argv[end-1]: HelloWorld
Disconnected...
[root@lwh testcpp]#

3. example-ssl.c

安装hiredis时要支持openssl

make USE_SSL=1
make install

但是链接openssl/ssl.h时报错!???

[root@lwh hiredis-master]# make USE_SSL=1
cc -std=c99 -pedantic -c -O3 -fPIC  -DHIREDIS_TEST_SSL -Wall -W -Wstrict-prototypes -Wwrite-strings -Wno-missing-field-initializers -g -ggdb alloc.c
cc -std=c99 -pedantic -c -O3 -fPIC  -DHIREDIS_TEST_SSL -Wall -W -Wstrict-prototypes -Wwrite-strings -Wno-missing-field-initializers -g -ggdb net.c
cc -std=c99 -pedantic -c -O3 -fPIC  -DHIREDIS_TEST_SSL -Wall -W -Wstrict-prototypes -Wwrite-strings -Wno-missing-field-initializers -g -ggdb hiredis.c
cc -std=c99 -pedantic -c -O3 -fPIC  -DHIREDIS_TEST_SSL -Wall -W -Wstrict-prototypes -Wwrite-strings -Wno-missing-field-initializers -g -ggdb sds.c
cc -std=c99 -pedantic -c -O3 -fPIC  -DHIREDIS_TEST_SSL -Wall -W -Wstrict-prototypes -Wwrite-strings -Wno-missing-field-initializers -g -ggdb async.c
cc -std=c99 -pedantic -c -O3 -fPIC  -DHIREDIS_TEST_SSL -Wall -W -Wstrict-prototypes -Wwrite-strings -Wno-missing-field-initializers -g -ggdb read.c
cc -std=c99 -pedantic -c -O3 -fPIC  -DHIREDIS_TEST_SSL -Wall -W -Wstrict-prototypes -Wwrite-strings -Wno-missing-field-initializers -g -ggdb sockcompat.c
cc -shared -Wl,-soname,libhiredis.so.1.0.1-dev -o libhiredis.so alloc.o net.o hiredis.o sds.o async.o read.o sockcompat.o
ar rcs libhiredis.a alloc.o net.o hiredis.o sds.o async.o read.o sockcompat.o
cc -std=c99 -pedantic -c -O3 -fPIC  -DHIREDIS_TEST_SSL -Wall -W -Wstrict-prototypes -Wwrite-strings -Wno-missing-field-initializers -g -ggdb test.c
cc -std=c99 -pedantic -c -O3 -fPIC  -DHIREDIS_TEST_SSL -Wall -W -Wstrict-prototypes -Wwrite-strings -Wno-missing-field-initializers -g -ggdb ssl.c
ar rcs libhiredis_ssl.a ssl.o
cc -o hiredis-test -O3 -fPIC  -DHIREDIS_TEST_SSL -Wall -W -Wstrict-prototypes -Wwrite-strings -Wno-missing-field-initializers -g -ggdb -I. test.o libhiredis.a libhiredis_ssl.a  -lssl -lcrypto -lssl -lcrypto -lpthread
/opt/rh/devtoolset-9/root/usr/libexec/gcc/x86_64-redhat-linux/9/ld: libhiredis_ssl.a(ssl.o): in function `redisInitOpenSSL':
/root/testcpp/hiredis-master/ssl.c:160: undefined reference to `OPENSSL_init_ssl'
/opt/rh/devtoolset-9/root/usr/libexec/gcc/x86_64-redhat-linux/9/ld: libhiredis_ssl.a(ssl.o): in function `redisCreateSSLContext':
/root/testcpp/hiredis-master/ssl.c:232: undefined reference to `TLS_client_method'
/opt/rh/devtoolset-9/root/usr/libexec/gcc/x86_64-redhat-linux/9/ld: /root/testcpp/hiredis-master/ssl.c:238: undefined reference to `SSL_CTX_set_options'
collect2: error: ld returned 1 exit status
make: *** [hiredis-test] Error 1
[root@lwh hiredis-master]#
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>#include <hiredis/hiredis.h>  // /usr/local/include/hiredis/hiredis.h
#include <hiredis/hiredis_ssl.h> // /usr/local/include/hiredis/hiredis_ssl.h#ifdef _MSC_VER
#include <winsock2.h> /* For struct timeval */
#endifint main(int argc, char **argv)
{unsigned int j;redisSSLContext *ssl;redisSSLContextError ssl_error;redisContext *c;redisReply *reply;if (argc < 4){printf("Usage: %s <host> <port> <cert> <key> [ca]\n", argv[0]);exit(1);}const char *hostname = (argc > 1) ? argv[1] : "127.0.0.1";int port = atoi(argv[2]);const char *cert = argv[3];const char *key = argv[4];const char *ca = argc > 4 ? argv[5] : NULL;redisInitOpenSSL();ssl = redisCreateSSLContext(ca, NULL, cert, key, NULL, &ssl_error);if (!ssl){printf("SSL Context error: %s\n",redisSSLContextGetError(ssl_error));exit(1);}struct timeval tv = {1, 500000}; // 1.5 secondsredisOptions options = {0};REDIS_OPTIONS_SET_TCP(&options, hostname, port);options.connect_timeout = &tv;c = redisConnectWithOptions(&options);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);}if (redisInitiateSSLWithContext(c, ssl) != REDIS_OK){printf("Couldn't initialize SSL!\n");printf("Error: %s\n", c->errstr);redisFree(c);exit(1);}/* PING server */reply = redisCommand(c, "PING");printf("PING: %s\n", reply->str);freeReplyObject(reply);/* Set a key */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);reply = redisCommand(c, "INCR counter");printf("INCR counter: %lld\n", reply->integer);freeReplyObject(reply);/* again ... */reply = redisCommand(c, "INCR counter");printf("INCR counter: %lld\n", reply->integer);freeReplyObject(reply);/* Create a list of numbers, from 0 to 9 */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);/* Disconnects and frees the context */redisFree(c);redisFreeSSLContext(ssl);return 0;
}

编译报错!待解决!有时间解决一下

[root@lwh testcpp]# gcc example-ssl.c  -o out -lhiredis -levent -lssl -lcrypto -lhiredis_ssl -L/usr/local/lib
/usr/local/lib/libhiredis_ssl.a(ssl.o): In function `redisInitOpenSSL':
/root/testcpp/hiredis-master/ssl.c:159: undefined reference to `OPENSSL_init_ssl'
/usr/local/lib/libhiredis_ssl.a(ssl.o): In function `redisCreateSSLContext':
/root/testcpp/hiredis-master/ssl.c:231: undefined reference to `TLS_client_method'
/root/testcpp/hiredis-master/ssl.c:237: undefined reference to `SSL_CTX_set_options'
collect2: error: ld returned 1 exit status
[root@lwh testcpp]# [root@lwh testcpp]# gcc test.c -o out -lhiredis -lssl -lcrypto -lhiredis_ssl
/opt/rh/devtoolset-9/root/usr/libexec/gcc/x86_64-redhat-linux/9/ld: /usr/local/lib/libhiredis_ssl.a(ssl.o): in function `redisInitOpenSSL':
/root/testcpp/hiredis-master/ssl.c:159: undefined reference to `OPENSSL_init_ssl'
/opt/rh/devtoolset-9/root/usr/libexec/gcc/x86_64-redhat-linux/9/ld: /usr/local/lib/libhiredis_ssl.a(ssl.o): in function `redisCreateSSLContext':
/root/testcpp/hiredis-master/ssl.c:231: undefined reference to `TLS_client_method'
/opt/rh/devtoolset-9/root/usr/libexec/gcc/x86_64-redhat-linux/9/ld: /root/testcpp/hiredis-master/ssl.c:237: undefined reference to `SSL_CTX_set_options'
collect2: error: ld returned 1 exit status
[root@lwh testcpp]# 

4. example-libevent-ssl.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>#include <hiredis/hiredis.h>  // /usr/local/include/hiredis/hiredis.h
#include <hiredis/hiredis_ssl.h> // /usr/local/include/hiredis/hiredis_ssl.h
#include <hiredis/async.h>
#include <hiredis/adapters/libevent.h>void getCallback(redisAsyncContext *c, void *r, void *privdata)
{redisReply *reply = r;if (reply == NULL)return;printf("argv[%s]: %s\n", (char *)privdata, reply->str);/* Disconnect after receiving the reply to GET */redisAsyncDisconnect(c);
}void connectCallback(const redisAsyncContext *c, int status)
{if (status != REDIS_OK){printf("Error: %s\n", c->errstr);return;}printf("Connected...\n");
}void disconnectCallback(const redisAsyncContext *c, int status)
{if (status != REDIS_OK){printf("Error: %s\n", c->errstr);return;}printf("Disconnected...\n");
}int main(int argc, char **argv)
{#ifndef _WIN32signal(SIGPIPE, SIG_IGN);
#endifstruct event_base *base = event_base_new();if (argc < 5){fprintf(stderr,"Usage: %s <key> <host> <port> <cert> <certKey> [ca]\n", argv[0]);exit(1);}const char *value = argv[1];size_t nvalue = strlen(value);const char *hostname = argv[2];int port = atoi(argv[3]);const char *cert = argv[4];const char *certKey = argv[5];const char *caCert = argc > 5 ? argv[6] : NULL;redisSSLContext *ssl;redisSSLContextError ssl_error;redisInitOpenSSL();ssl = redisCreateSSLContext(caCert, NULL,cert, certKey, NULL, &ssl_error);if (!ssl){printf("Error: %s\n", redisSSLContextGetError(ssl_error));return 1;}redisAsyncContext *c = redisAsyncConnect(hostname, port);if (c->err){/* Let *c leak for now... */printf("Error: %s\n", c->errstr);return 1;}if (redisInitiateSSLWithContext(&c->c, ssl) != REDIS_OK){printf("SSL Error!\n");exit(1);}redisLibeventAttach(c, base);redisAsyncSetConnectCallback(c, connectCallback);redisAsyncSetDisconnectCallback(c, disconnectCallback);redisAsyncCommand(c, NULL, NULL, "SET key %b", value, nvalue);redisAsyncCommand(c, getCallback, (char *)"end-1", "GET key");event_base_dispatch(base);redisFreeSSLContext(ssl);return 0;
}
[root@lwh testcpp]# gcc example-libevent-ssl.c  -o out -lhiredis -levent -lssl -lcrypto -lhiredis_ssl -L/usr/local/lib
/usr/local/lib/libhiredis_ssl.a(ssl.o): In function `redisInitOpenSSL':
/root/testcpp/hiredis-master/ssl.c:159: undefined reference to `OPENSSL_init_ssl'
/usr/local/lib/libhiredis_ssl.a(ssl.o): In function `redisCreateSSLContext':
/root/testcpp/hiredis-master/ssl.c:231: undefined reference to `TLS_client_method'
/root/testcpp/hiredis-master/ssl.c:237: undefined reference to `SSL_CTX_set_options'
collect2: error: ld returned 1 exit status
[root@lwh testcpp]# 

5. example-push.c

Are you sure you’re connected to redis-server >= 6.0.0?
所以要保证你的redis版本大于等于6.0.0

/** Copyright (c) 2020, Michael Grunder <michael dot grunder at gmail dot com>** All rights reserved.** Redistribution and use in source and binary forms, with or without* modification, are permitted provided that the following conditions are met:**   * Redistributions of source code must retain the above copyright notice,*     this list of conditions and the following disclaimer.*   * Redistributions in binary form must reproduce the above copyright*     notice, this list of conditions and the following disclaimer in the*     documentation and/or other materials provided with the distribution.*   * Neither the name of Redis nor the names of its contributors may be used*     to endorse or promote products derived from this software without*     specific prior written permission.** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE* POSSIBILITY OF SUCH DAMAGE.*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hiredis/hiredis.h>#define KEY_COUNT 5#define panicAbort(fmt, ...)                                                            \do                                                                                  \{                                                                                   \fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, __LINE__, __func__, __VA_ARGS__); \exit(-1);                                                                       \} while (0)static void assertReplyAndFree(redisContext *context, redisReply *reply, int type)
{if (reply == NULL)panicAbort("NULL reply from server (error: %s)", context->errstr);if (reply->type != type){if (reply->type == REDIS_REPLY_ERROR)fprintf(stderr, "Redis Error: %s\n", reply->str);panicAbort("Expected reply type %d but got type %d", type, reply->type);}freeReplyObject(reply);
}/* Switch to the RESP3 protocol and enable client tracking */
static void enableClientTracking(redisContext *c)
{redisReply *reply = redisCommand(c, "HELLO 3");if (reply == NULL || c->err){panicAbort("NULL reply or server error (error: %s)", c->errstr);}if (reply->type != REDIS_REPLY_MAP){fprintf(stderr, "Error: Can't send HELLO 3 command.  Are you sure you're ");fprintf(stderr, "connected to redis-server >= 6.0.0?\nRedis error: %s\n",reply->type == REDIS_REPLY_ERROR ? reply->str : "(unknown)");exit(-1);}freeReplyObject(reply);/* Enable client tracking */reply = redisCommand(c, "CLIENT TRACKING ON");assertReplyAndFree(c, reply, REDIS_REPLY_STATUS);
}void pushReplyHandler(void *privdata, void *r)
{redisReply *reply = r;int *invalidations = privdata;/* Sanity check on the invalidation reply */if (reply->type != REDIS_REPLY_PUSH || reply->elements != 2 ||reply->element[1]->type != REDIS_REPLY_ARRAY ||reply->element[1]->element[0]->type != REDIS_REPLY_STRING){panicAbort("%s", "Can't parse PUSH message!");}/* Increment our invalidation count */*invalidations += 1;printf("pushReplyHandler(): INVALIDATE '%s' (invalidation count: %d)\n",reply->element[1]->element[0]->str, *invalidations);freeReplyObject(reply);
}/* We aren't actually freeing anything here, but it is included to show that we can* have hiredis call our data destructor when freeing the context */
void privdata_dtor(void *privdata)
{unsigned int *icount = privdata;printf("privdata_dtor():  In context privdata dtor (invalidations: %u)\n", *icount);
}int main(int argc, char **argv)
{unsigned int j, invalidations = 0;redisContext *c;redisReply *reply;const char *hostname = (argc > 1) ? argv[1] : "127.0.0.1";int port = (argc > 2) ? atoi(argv[2]) : 6379;redisOptions o = {0};REDIS_OPTIONS_SET_TCP(&o, hostname, port);/* Set our context privdata to the address of our invalidation counter.  Each* time our PUSH handler is called, hiredis will pass the privdata for context.** This could also be done after we create the context like so:**    c->privdata = &invalidations;*    c->free_privdata = privdata_dtor;*/REDIS_OPTIONS_SET_PRIVDATA(&o, &invalidations, privdata_dtor);/* Set our custom PUSH message handler */o.push_cb = pushReplyHandler;c = redisConnectWithOptions(&o);if (c == NULL || c->err)panicAbort("Connection error:  %s", c ? c->errstr : "OOM");/* Enable RESP3 and turn on client tracking */enableClientTracking(c);/* Set some keys and then read them back.  Once we do that, Redis will deliver* invalidation push messages whenever the key is modified */for (j = 0; j < KEY_COUNT; j++){reply = redisCommand(c, "SET key:%d initial:%d", j, j);assertReplyAndFree(c, reply, REDIS_REPLY_STATUS);reply = redisCommand(c, "GET key:%d", j);assertReplyAndFree(c, reply, REDIS_REPLY_STRING);}/* Trigger invalidation messages by updating keys we just read */for (j = 0; j < KEY_COUNT; j++){printf("            main(): SET key:%d update:%d\n", j, j);reply = redisCommand(c, "SET key:%d update:%d", j, j);assertReplyAndFree(c, reply, REDIS_REPLY_STATUS);printf("            main(): SET REPLY OK\n");}printf("\nTotal detected invalidations: %d, expected: %d\n", invalidations, KEY_COUNT);/* PING server */redisFree(c);
}
[root@lwh testcpp]# gcc example-push.c  -o out -lhiredis
[root@lwh testcpp]# ./out main(): SET key:0 update:0
pushReplyHandler(): INVALIDATE 'key:0' (invalidation count: 1)main(): SET REPLY OKmain(): SET key:1 update:1
pushReplyHandler(): INVALIDATE 'key:1' (invalidation count: 2)main(): SET REPLY OKmain(): SET key:2 update:2
pushReplyHandler(): INVALIDATE 'key:2' (invalidation count: 3)main(): SET REPLY OKmain(): SET key:3 update:3
pushReplyHandler(): INVALIDATE 'key:3' (invalidation count: 4)main(): SET REPLY OKmain(): SET key:4 update:4
pushReplyHandler(): INVALIDATE 'key:4' (invalidation count: 5)main(): SET REPLY OKTotal detected invalidations: 5, expected: 5
privdata_dtor():  In context privdata dtor (invalidations: 5)
[root@lwh testcpp]#

MyDemo

hiredis_hash_test.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>#include <hiredis/hiredis.h>int main()
{const char *ip = "127.0.0.1"; //ipint port = 6379;           //portredisContext *context;        //管理连接服务器的指针redisReply *reply;              //执行命令后返回的结构体指针,存储了处理结果//1.连接redis服务器context = redisConnect(ip, port);if (context == NULL || context->err){if (context){printf("Connection error contex->errstr: %s\n", context->errstr);redisFree(context);}else{printf("Connection error: can't allocate redis context\n");}exit(1);}//2.执行操作reply = (redisReply *)redisCommand(context, "hmset user name zhangsanfeng age 24 sex man password 123456");if (reply->type == 5){printf("命令执行完毕,状态码:%s\n", reply->str);}freeReplyObject(reply);// 将hash的value值读出reply = (redisReply *)redisCommand(context, "hgetall user");if (reply->type == 2){//遍历数组for (int i = 0; i < reply->elements; i += 2){printf("%s : %s\n", reply->element[i]->str, reply->element[i + 1]->str);}}freeReplyObject(reply);//3.断开连接redisFree(context);return 0;
}
[root@lwh testcpp]# gcc test.c  -o out -lhiredis
[root@lwh testcpp]# ./out
命令执行完毕,状态码:OK
name : zhangsanfeng
age : 24
sex : man
password : 123456
[root@lwh testcpp]# 

Redis 学习 - hiredis(官网 2021-01-06)相关推荐

  1. 潢川高中2021高考成绩查询,信阳市教育体育局官网2021潢川中招成绩查询系统

    信阳市教育体育局官网2021潢川中招成绩查询系统 信阳市教育体育局官网2021潢川中招成绩查询系统 信阳教育体育局官网(http://jytyj.xinyang.gov.cn)是2021潢川中考官方网 ...

  2. 2021潢川中学高考成绩查询,信阳市教育体育局官网2021潢川中招成绩查询系统

    信阳市教育体育局官网2021潢川中招成绩查询系统 信阳教育体育局官网(http://jytyj.xinyang.gov.cn)是2021潢川中考官方网站,信阳市教育局网站jytyj.xinyang.g ...

  3. Redis各个命令官网地址

    在学习Redis的时候,熟悉redis的各种操作命令是非常重要的,因为Redis各种操作都是需要各种命令的参与才能得到正确的结果,下面给出Redis官网命令地址 官网命令地址:https://redi ...

  4. 如何学习一个新的计算机概念(协议等),如snmp? 上官网学习【官网集合】

    snmp学习,不要仅仅只在百度上翻阅.要养成习惯,去snmp的官网,读英文官方文档.这里会有一手的教程.源代码.命令行. Qt官网:https://www.qt.io .https://doc.qt. ...

  5. Redis和RedisClient 官网下载方式

    1.0 先说怎么下载 RedisClient 如果不想看怎么从官网下载的具体步骤,也可以>点击直接下载RedisClient(提示:如果点击下载地址无效,有可能官网下载地址有所变动,请看下面步骤 ...

  6. hive on tez学习之官网和源码

    Hive on Tez - Apache Hive - Apache Software Foundation 简单来说 hive是根本,执行引擎目前用过spark 和mr,现在是tez. 一般来说mr ...

  7. 推荐一些适合学习的官网

    文章目录 1.腾讯课堂 2.开课吧 3.起点中文网 4.51CTO学院 5.课工场 6.MDN Web文档 7.阿里云开发者社区 8.蛮牛教育 9.腾讯游戏学院 10.廖雪峰的官方网站 11.虎课网( ...

  8. Avrora学习笔记(官网)

    Avrora:有精确时钟特性可扩展的传感器网络模拟器. Avrora总的来说既是一个传感网程序的模拟器,也为传感网程序提供了一个分析框架. 1.-platform=micaz:指定程序运行的节点模拟平 ...

  9. VisualC++ 2010 Express 学习版官网下载安装及使用

    百度网盘链接:https://pan.baidu.com/s/1PmLRyt25FXhCcMDSRt4kAg 提取码:un2e ( 很小不到4M) 官网地址:https://my.visualstud ...

  10. Play Framework_学习_官网Yabe博客指南(一)

    从 start -> end 学习 Play Framework 1.4.3 框架搭建一个博客系统--- 虽然这个框架很少看到Java开发者使用,但是也快速开发的一个很不错的框架,它对你代码要求 ...

最新文章

  1. ASP.NET画图控件 Chart Control 免费控件
  2. 想成为优秀的技术人员你必须做到的几件事情
  3. python编程游戏手机版_利用Python开发手机同款游戏:开心消消乐
  4. 【逆水寒三周年】大型MMO项目UI管理的价值与责任
  5. 445端口关闭后目录文件共享怎么办
  6. Ubuntu kylin 14.04 LTS上安装opencv
  7. 用虚拟机把ubuntu安装到TF卡上
  8. jeeCMS首页加载流程
  9. 两个瓶子水怎样一样多_同事每天比我多睡两个小时!省下70万买了地铁站附近房子 杭州姑娘却感叹买房时一定是脑子进了水……...
  10. python 神经网络原理_神经网络理论基础及Python实现
  11. php编写一个投票程序,实例学习PHP之投票程序篇(一)
  12. makefile how to
  13. Understanding Unix/Linux Programming-事件驱动编程:编写一个视频游戏
  14. 【语音编码】基于matlab ADPCM编解码【含Matlab源码 553期】
  15. 未来教育计算机二级题库如何更新,未来教育的计算机二级题库准吗?
  16. 安利一款SOLIDWORKS插件,可一键帮你分离配置那种!
  17. 调查报告:创意行业是否为远程办公做好准备?
  18. PHP操作redis详细讲解
  19. linux中 不在sudoers文件中此事将被报告
  20. 【微信早安定时推送消息】微信公众号定时推送早安消息 带天气、纪念日、生日、定时推送等(完整代码)

热门文章

  1. [OpenHarmony RK3568] (二)基础开发
  2. 2018年上半年UI领域主要的13个设计趋势
  3. 超分辨率:Photo-Realistic Single Image Super-Resolution Using a Generative Adversarial Network论文翻译
  4. Python强智教务系统模拟登录的两种方式
  5. iOS逆向:【ARM 移位操作】(LSL、ASL、LSR、ASR、ROR、RRX)
  6. Dreamweaver 8 时间轴及创建时间轴动画(转)
  7. android直接gpu中取纹理数据,[Android-Camera开发]Android平台Camera实时预览数据处理即实时滤镜实现方法探讨(二)--GPUImage探讨...
  8. 一文读懂自动驾驶传感器之激光雷达、毫米波雷达、超声波雷达及摄像头
  9. 史上最全的WSL安装教程
  10. Python-pygsheets模块(读写Google谷歌文档)