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,实现更高性能的数据缓存与消息队列吧!

相关推荐
R-sz25 分钟前
redis缓存工具类【当缓存未命中时,自动调用数据加载函数从数据库获取数据并存入Redis】
redis·spring·缓存
hunjinYang30 分钟前
缓存常见问题:缓存穿透、缓存雪崩以及缓存击穿
redis·缓存
Yurko1336 分钟前
【C语言】函数指针及其应用
c语言·开发语言·学习
熙曦Sakura1 小时前
【MySQL】C语言连接
c语言·mysql·adb
woho7788992 小时前
伊吖学C笔记(4、循环、自定义函数、二级菜单)
c语言·开发语言·笔记
算法歌者2 小时前
[C]基础16.数据在内存中的存储
c语言
极客智谷2 小时前
缓存架构方案:Caffeine + Redis 双层缓存架构深度解析
redis·缓存·架构
睡觉z3 小时前
MySQL数据库初体验
数据库·mysql·oracle
意识成长4 小时前
国产化redis 替代产品tendis 安装
redis
CC同学呀5 小时前
从0到1:多医院陪诊小程序开发笔记(上)
数据库·笔记