$ cd redis-6.0.9/deps/hiredis
$ make
$ sudo make install
# 在/usr/local/include /usr/local/lib 中自动添加库文件、库<br />gcc -o redis-test redis-test.c -I /usr/local/include/hiredis -L /usr/local/lib -lhiredis <br />将 LD_LIBRARY_PATH=/usr/local/lib 添加到 .bash_profile<br /> <br />开发头文件 :<br />#include <hiredis/hiredis.h>
实际开发过程中:需要根据业务来gen command string 即标红部分
执行对每个命令进行封装(确保 redisCommand-freeReplyObject 一一对应),如:
void flushdb(redisContext context)
{
redisReply reply = (redisReply *)redisCommand(context, “FLUSHDB”);
printf(“reply->type: %d\n”, reply->type);
if (reply->type == REDIS_REPLY_STATUS)
{
printf(“FLUSHDB OK\n”);
}
printf(“reply->str: %s\n”, reply->str);
freeReplyObject(reply);
}
连接redis redisConnect
redisContext *context = redisConnect(“127.0.0.1”, 6379);
if (context == NULL || context->err) {
if (context) {
printf(“%s\n”, context->errstr);
} else {
printf(“redisConnect error\n”);
}
exit(EXIT_FAILURE);
}配置redis命令 redisCommand 原型: fmt
redisReply reply = (redisReply )redisCommand(context, “SET %s %s”, key, val); // 标红:redis 命令 get/set等等都是通过 redisCommand 来实现, 执行redis命令的结果全部由结构体 reply 来保存(不管什么数据类型,或错误信息)
if (reply->type == REDIS_REPLY_STATUS) {
printf(“SET %s %s\n”, key, val);
}
freeReplyObject(reply); // 每执行完一个redisCommand后必须释放,缺失会造成内存泄漏
释放redis redisFree
redisFree(context);