学习总结一下官方发布的C版本客户端 hiredis,了解hiredis 客户端大致实现细节。在理解代码之间需要了解通信协议的特点,我上一篇转载的文章已经有过介绍,大家可以去看一下。
hiredis 提供了同步、异步访问,异步 API 需要与一些事件库协同工作,主要看一下同步API的实现。
hiredis 与服务端通信的API比较简单,主要有这几个步骤:
- 建立连接
- 发送命令
- 等待结果并处理
- 释放连接
一、相关数据结构
redisContext 保存连接建立后的上下文。 err 保存错误码,如果为0表示没错,如果非0那么错误说明保存在 errstr 中;fd是连接建立后的套接字;flags表示连接的标识;obuf 保存要向 redis-server 发送的命令内容;reader 用来读取从服务端返回的消息,redisReader中的buf成员用来保存内容;connection_type 表示连接类型,有两种分别是REDIS_CONN_TCP 和 REDIS_CONN_UNIX;timeout 是连接时指定的超时时间。
/* Context for a connection to Redis */
typedef struct redisContext {
int err; /* Error flags, 0 when there is no error */
char errstr[128]; /* String representation of error when applicable */
int fd;
int flags;
char *obuf; /* Write buffer */
redisReader *reader; /* Protocol reader */
enum redisConnectionType connection_type;
struct timeval *timeout;
struct {
char *host;
char *source_addr;
int port;
} tcp;
struct {
char *path;
} unix_sock;
} redisContext;
/* This is the reply object returned by redisCommand() */
typedef struct redisReply {
int type; /* REDIS_REPLY_* */
long long integer; /* The integer when type is REDIS_REPLY_INTEGER */
size_t len; /* Length of string */
char *str; /* Used for both REDIS_REPLY_ERROR and REDIS_REPLY_STRING */
size_t elements; /* number of elements, for REDIS_REPLY_ARRAY */
s

本文介绍了Redis官方发布的C语言客户端Hiredis,包括其数据结构、API使用,如建立连接、发送命令、接收结果和释放连接。文章通过一个实例展示了Hiredis的基本操作流程,帮助读者掌握Hiredis的同步API应用。
最低0.47元/天 解锁文章
9828

被折叠的 条评论
为什么被折叠?



