当前位置: 首页 > backend >正文

Redis C语言连接教程

一、源码编译与安装

  1. 获取源码

    git clone https://github.com/redis/hiredis.git
    cd hiredis
    
  2. 编译库

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

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

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

二、连接并测试

新建 main.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 barredisReply *reply = redisCommand(ctx, "SET foo bar");printf("SET 返回: %s\n", reply->str);freeReplyObject(reply);// 执行 GET fooreply = redisCommand(ctx, "GET foo");printf("GET 返回: %s\n", reply->str);freeReplyObject(reply);// 关闭连接redisFree(ctx);return 0;
}

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

cc main.c -lhiredis -o test_redis
./test_redis# 输出:
# SET 返回: OK
# GET 返回: bar

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

三、发送命令

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

  • 示例:

    // 自增计数器
    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 判断结果类型并提取值,常见类型及字段:

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)

管道示例

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

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

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 为例:

#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;
}

七、更多资源

  • 🔗 hiredis GitHub:https://github.com/redis/hiredis
  • 🔗 API 文档docs/hiredis
  • 🔗 事件适配器示例hiredis/adapters/

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

http://www.xdnf.cn/news/9263.html

相关文章:

  • Linux 环境下C、C++、Go语言编译环境搭建秘籍
  • 常见编码小结
  • 常见JDK安装配置
  • springboot 笔记
  • Redis核心数据结构操作指南:字符串、哈希、列表详解
  • 【K8S】K8S基础概念
  • Java spingboot项目 在docker运行,需要含GDAL的JDK
  • 飞牛fnNAS手机相册备份及AI搜图
  • 博图SCL基础知识-表达式及赋值运算
  • 甲醇 燃料 不也有碳排放吗?【AI回答版】
  • 得物Java开发面试题及参考答案(下)
  • Linux操作系统概述
  • 【Canvas与日月星辰】烈日当空
  • 关于git的使用
  • 【漏洞与预防】Microsoft Windows 文件资源管理器欺骗漏洞预防
  • 【免费】【无需登录/关注】Base64 图片转换工具网页
  • 【Java】DelayQueue
  • LangGraph(七)——Workflows
  • 基于物联网(IoT)的电动汽车(EVs)智能诊断
  • Java组合、聚合与关联:核心区别解析
  • AWS WebRTC:获取信令服务节点和ICE服务节点
  • 深度解读 Qwen3 大语言模型的关键技术
  • 【Elasticsearch】ingest对于update操作起作用吗?
  • Android15 Camera Hal设置logLevel控制日志输出
  • vue2使用el-tree实现两棵树间节点的拖拽复制
  • LeetCode 2894.分类求和并作差:数学O(1)一行解决
  • Java提取markdown中的表格
  • go并发与锁之sync.Mutex入门
  • 国11阶乘约数-质因数分解
  • C/C++的OpenCV的锐化