Redis C语言连接教程

一、源码编译与安装

  1. 获取源码

    bash 复制代码
    git clone https://github.com/redis/hiredis.git
    cd hiredis
  2. 编译库

    bash 复制代码
    make
    • Linux 下生成 libhiredis.so,macOS 下生成 libhiredis.dylib
  3. 安装到系统(可选)

    bash 复制代码
    sudo make install
    • 默认将头文件安装到 /usr/local/include/hiredis,库文件安装到 /usr/local/lib

如果不想安装到系统目录,也可以将生成的库和头文件拷贝到项目目录,自行通过编译参数指定路径。

二、连接并测试

新建 main.c,演示最基本的连接、设置和获取操作:

c 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <hiredis/hiredis.h>

int main(void) {
    // 建立到 Redis 的连接(默认 127.0.0.1:6379)
    redisContext *ctx = redisConnect("127.0.0.1", 6379);
    if (ctx == NULL || ctx->err) {
        if (ctx) {
            fprintf(stderr, "连接错误: %s\n", ctx->errstr);
            redisFree(ctx);
        } else {
            fprintf(stderr, "无法分配 redisContext\n");
        }
        exit(EXIT_FAILURE);
    }

    // 执行 SET foo bar
    redisReply *reply = redisCommand(ctx, "SET foo bar");
    printf("SET 返回: %s\n", reply->str);
    freeReplyObject(reply);

    // 执行 GET foo
    reply = redisCommand(ctx, "GET foo");
    printf("GET 返回: %s\n", reply->str);
    freeReplyObject(reply);

    // 关闭连接
    redisFree(ctx);
    return 0;
}

编译并运行(若已 make install):

bash 复制代码
cc main.c -lhiredis -o test_redis
./test_redis

# 输出:
# SET 返回: OK
# GET 返回: bar

若未安装到系统路径,可加上 -I/path/to/hiredis-L/path/to/hiredis

三、发送命令

  • 使用 redisCommand() 发送任意 Redis 命令,返回 redisReply*

  • 示例:

    c 复制代码
    // 自增计数器
    redisReply *r = redisCommand(ctx, "INCR page_views");
    printf("访问量: %lld\n", r->integer);
    freeReplyObject(r);
    
    // 向列表头插入用户名
    r = redisCommand(ctx, "LPUSH recent_users %s", username);
    freeReplyObject(r);

四、处理回复

根据 reply->type 判断结果类型并提取值,常见类型及字段:

c 复制代码
switch (reply->type) {
  case REDIS_REPLY_STRING:
    printf("字符串: %s\n", reply->str);
    break;
  case REDIS_REPLY_INTEGER:
    printf("整数: %lld\n", reply->integer);
    break;
  case REDIS_REPLY_ARRAY:
    for (size_t i = 0; i < reply->elements; i++) {
        printf("元素[%zu]: %s\n", i, reply->element[i]->str);
    }
    break;
  case REDIS_REPLY_NIL:
    puts("空回复");
    break;
  case REDIS_REPLY_STATUS:
    printf("状态: %s\n", reply->str);
    break;
  case REDIS_REPLY_ERROR:
    fprintf(stderr, "错误: %s\n", reply->str);
    break;
}
freeReplyObject(reply);

使用完 redisReply 后,务必调用 freeReplyObject() 释放内存。

五、管道(Pipelining)与事务(Transactions)

管道示例

将多条命令打包,减少网络往返:

c 复制代码
redisAppendCommand(ctx, "SET a 1");
redisAppendCommand(ctx, "SET b 2");
redisAppendCommand(ctx, "MGET a b");

redisReply *r;
for (int i = 0; i < 3; i++) {
    redisGetReply(ctx, (void**)&r);
    // 处理 r ...
    freeReplyObject(r);
}

事务示例

使用 MULTI/EXEC

c 复制代码
redisReply *r = redisCommand(ctx, "MULTI");
freeReplyObject(r);

redisAppendCommand(ctx, "INCR counter");
redisAppendCommand(ctx, "INCR counter");

r = redisCommand(ctx, "EXEC");
if (r->type == REDIS_REPLY_ARRAY) {
    printf("执行了 %zu 条命令\n", r->elements);
}
freeReplyObject(r);

六、与事件驱动框架集成

hiredis 提供多种事件循环适配器,可实现非阻塞 I/O:

  • libevent#include <hiredis/adapters/libevent.h>
  • libuv#include <hiredis/adapters/uv.h>
  • ae (Redis 内置):#include <hiredis/adapters/ae.h>

以 libevent 为例:

c 复制代码
#include <event.h>
#include <hiredis/hiredis.h>
#include <hiredis/adapters/libevent.h>

int main(void) {
    struct event_base *base = event_base_new();
    redisContext *ctx = redisConnect("127.0.0.1", 6379);
    redisLibeventAttach(ctx, base);

    // 异步发送 PING,回调中处理结果
    redisAsyncCommand(ctx, [](redisAsyncContext*, void*, void*) {
        printf("PONG\n");
    }, NULL, "PING");

    event_base_dispatch(base);
    return 0;
}

七、更多资源

通过本文,你已掌握在 C 项目中使用 hiredis:从编译、连接、命令交互,到高级管道、事务及事件驱动集成的全流程。开始在你的 C 服务中引入 Redis,实现更高性能的数据缓存与消息队列吧!

相关推荐
TDengine (老段)17 分钟前
TDengine IDMP 背后的技术三问:目录、标准与情景
大数据·数据库·物联网·算法·时序数据库·iot·tdengine
Crazy learner22 分钟前
C语言fgets函数详解:安全读取字符串的利器
c语言·开发语言·算法
爱学习的小熊猫_1 小时前
在Linux上部署RabbitMQ、Redis、ElasticSearch
linux·redis·elasticsearch·中间件·rabbitmq
HW-BASE1 小时前
C语言控制语句练习题1
c语言·开发语言·单片机·算法·嵌入式·c
ID_180079054731 小时前
python采集拍立淘按图搜索API接口,json数据参考
大数据·数据库·python·json
不辉放弃2 小时前
阿里云 Flink
数据库·大数据开发·阿里云flink
奶黄小甜包2 小时前
C语言零基础第9讲:指针基础
c语言·笔记·学习
泽虞2 小时前
C语言深度语法掌握笔记:语法陷阱、内存管理、指针系统
c语言·笔记·面试
平生不喜凡桃李3 小时前
Linux 线程同步与互斥
java·jvm·redis
knd_max3 小时前
C语言:指针(1-2)
c语言