一、概述
Redis的C/C++编程,可以借助Hiredis。我们可以借助Hiredis提供的接口 ,实现对redis的读写操作。
Hiredis是一个Redis的C客户端库函数,基本实现了Redis的协议的最小集。
二、hiredis的使用
1、hiredis安装
安装步骤:
1)解压:tar -zxvf hiredis-0.14.0.tar.gz
2)编译:make
3)安装:make install
2、同步API接口的说明
项目中我一般使用的hireds接口都是同步的API,所谓同步意思就是使用阻塞的方式向redis server下发消息。
1)连接redis数据库函数redisConnect
redisContext *redisConnect(const char *ip, int port);
参数说明
• port:为redis数据监听的端口号,redis默认监听的端口号为6379
• ip:为redis数据库的IP地址,可以是远程的,也可以是本地的127.0.0.1
返回值
返回值是一个指向redisContext对象,可以不用了解这个对象的具体组成部分,只需要知道怎么使用就可以了。下面是其定义
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;
使用实例:
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)发送需要执行的命令函数redisCommand
void *redisCommand(redisContext *c, const char *format,

本文介绍了如何使用Hiredis库进行Redis的C/C++编程,包括安装配置、同步API接口使用方法及连接池设计等核心内容。通过具体示例展示了连接数据库、执行命令等操作。

4721

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



