连接

使用 hiredis 连接到服务器。

基本同步连接

下面的示例创建了一个到本地 Redis 服务器的简单同步连接,并在使用 redisFree() 关闭连接之前测试了该连接。redisConnect() 函数仅将主机名和端口作为参数,并返回一个上下文对象。

#include <stdio.h>

#include <hiredis/hiredis.h>
    .
    .
    .

// 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);

异步连接

您也可以使用异步 API 连接到 Redis。创建上下文的 redisAsyncConnect() 调用类似于同步函数 redisConnect(),但它在连接完成之前立即返回上下文对象。它允许您提供回调函数,以便在连接成功时响应或处理可能发生的任何错误。

以下代码创建了一个异步连接并设置了上下文回调。请注意,您还必须包含 async.h 头文件才能访问异步 API。

#include <stdio.h>

#include <hiredis/hiredis.h>
#include <hiredis/async.h>
    .
    .
    .

redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);

if (c->err) {
    printf("Error: %s\n", c->errstr);
    return 1;
}

// Set callbacks to respond to successful or unsuccessful
// connection and disconnection.
redisAsyncSetConnectCallback(c, connectCallback);
redisAsyncSetDisconnectCallback(c, disconnectCallback);

char *key = "testkey";
char *value = "testvalue";

// Status reply is ignored.
redisAsyncCommand(c, NULL, NULL, "SET %s %s", key, value);

// Reply handled by `getCallback()` function.
redisAsyncCommand(c, getCallback, key, "GET %s", key);

回调函数具有简单的签名,接收上下文对象和状态码。有关可能的状态码列表,请参阅处理错误

void connectCallback(const redisAsyncContext *c, int status) {
    if (status != REDIS_OK) {
        printf("Error: %s\n", c->errstr);
        return;
    }
    printf("Connected...\n");
}

void disconnectCallback(const redisAsyncContext *c, int status) {
    if (status != REDIS_OK) {
        printf("Error: %s\n", c->errstr);
        return;
    }
    printf("Disconnected...\n");
}

使用 redisAsyncCommand() 函数通过异步连接发出 Redis 命令。这类似于等效的同步函数 redisCommand(),但也允许您提供回调函数和自定义数据指针来处理命令的响应。有关更多信息,请参阅构建异步命令

请注意,完成连接使用后,通常应从回调函数中异步断开连接。使用 redisAsyncDisconnect() 优雅地断开连接,让挂起的命令执行并激活其回调。使用 redisAsyncFree() 立即断开连接。如果这样做,则已执行命令的任何挂起回调将使用 NULL 回复指针调用。

评价本页
回到顶部 ↑