学习

C 和 Redis

Ajeet Raina
作者
Ajeet Raina, Redis 前开发者增长经理

查找教程、示例和技术文章,帮助您使用 Redis 和 C 进行开发。

入门指南#

要在 C 中使用 Redis,您需要一个 C Redis 客户端。对于您使用 C 和 Redis 的第一步,本文将展示如何使用推荐的库: hiredis

步骤 1. 安装先决条件#

1.0.0 版本标志着 Hiredis 的第一个稳定发布。请按照以下步骤安装先决条件软件包,以便编译最新版本的 hiredis。

 brew install gcc make

运行以下命令启动 Redis 服务器

 redis-server

步骤 2. 安装和编译 hiredis#

wget https://github.com/redis/hiredis/archive/master.zip
 make
 make install

步骤 3. 复制以下 C 代码:#

 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <hiredis/hiredis.h>

 int main (int argc, char **argv) {
   redisReply *reply;
   redisContext *c;

   c = redisConnect("127.0.0.1", 6381);
   if (c->err) {
       printf("error: %s\n", c->errstr);
       return 1;
   }

   /* PINGs */
   reply = redisCommand(c,"PING %s", "Hello World");
   printf("RESPONSE: %s\n", reply->str);
   freeReplyObject(reply);

   redisFree(c);
 }

步骤 4. 编译代码#

 gcc redistest.c -o redistest -I /usr/local/include/hiredis -lhiredis

步骤 5. 测试代码#

 ./redistest
 RESPONSE: Hello World

更多 C 客户端资源#

  • hiredis-cluster - 用于 Redis Cluster 的 C 客户端库
  • libredis - 一个基于 C 的通用低级 PHP 扩展和 Redis 客户端库,专注于性能、通用性以及与多个 Redis 服务器进行高效并行通信。
  • hiredispool - 为 hiredis 提供连接池和自动重连功能。它也非常简洁,易于定制。