hiredis 指南 (C)

将 C 应用程序连接到 Redis 数据库。

hiredis 是 Redis 的 C 语言 客户端。以下部分解释了如何安装 hiredis 并将您的应用程序连接到 Redis 数据库。

hiredis 需要一个正在运行的 Redis 或 Redis Stack 服务器。有关 Redis 安装说明,请参阅入门

构建和安装

Github 仓库 克隆或下载 hiredis 源代码。然后,在终端中进入 hiredis 文件夹并运行 make 命令来构建 hiredis 的动态加载库(在 MacOS 上命名为 libhiredis.dylib,在 Linux 上命名为 libhiredis.so)。您可以将此库复制到您的项目文件夹,或者运行 sudo make install 将其安装到 /usr/local/lib

连接和测试

下面示例中的代码连接到服务器,使用 SETGET 存储和检索字符串键,最后关闭连接。代码解释紧随示例之后。

#include <stdio.h>

#include <hiredis/hiredis.h>

int main() {
    // The `redisContext` type represents the connection
    // to the Redis server. Here, we connect to the
    // default host and port.
    redisContext *c = redisConnect("127.0.0.1", 6379);

    // Check if the context is null or if a specific
    // error occurred.
    if (c == NULL || c->err) {
        if (c != NULL) {
            printf("Error: %s\n", c->errstr);
            // handle error
        } else {
            printf("Can't allocate redis context\n");
        }

        exit(1);
    }

    // Set a string key.
    redisReply *reply = redisCommand(c, "SET foo bar");
    printf("Reply: %s\n", reply->str); // >>> Reply: OK
    freeReplyObject(reply);

    // Get the key we have just stored.
    reply = redisCommand(c, "GET foo");
    printf("Reply: %s\n", reply->str); // >>> Reply: bar
    freeReplyObject(reply);

    // Close the connection.
    redisFree(c);
}

对于实际项目,您会使用 makefile 构建代码,但对于这个简单的测试,您可以将其放在一个名为 main.c 的文件中,并使用以下命令构建它。(如果您未使用 make install 安装 hiredis,那么您还应该使用 -I 选项指定包含 hiredis 头文件的文件夹。)

cc main.c -L/usr/local/lib -lhiredis

默认的可执行文件名是 a.out。如果您从终端运行此文件,您应该看到以下输出

% ./a.out                             
Reply: OK
Reply: bar

代码首先使用 redisConnect() 打开连接,供所有后续命令使用。有关连接到 Redis 的更多信息,请参阅连接

redisCommand() 函数向服务器发出命令,每个命令都返回一个 redisReply 指针。此处,回复是一个字符串,您可以使用回复的 str 字段访问它。redisCommand() 调用会为回复分配内存,因此在使用完毕后,您应该使用 freeReplyObject() 释放它。更多信息请参阅发出命令处理回复

最后,您应该调用 redisFree() 关闭与 Redis 的连接。对于这个简短的测试程序来说,这并不是严格必要的,但实际代码通常会打开并使用许多连接。使用完毕后必须释放它们以防止错误。

更多信息

hiredis Github 仓库包含示例和详细信息,如果您使用 hiredis 为另一种编程语言实现更高级别的客户端,这些信息可能会很有用。还有示例展示了如何使用 hiredis 适配器头文件与各种事件处理框架集成。

有关更多信息和示例,请参阅本节中的其他页面。

评价此页面
返回顶部 ↑