将 hiredis 与 libevent 应用集成

hiredislibevent 框架结合使用。

libevent 库提供了一个事件循环的实现,允许您异步调用函数以响应事件。本指南介绍如何使用 hiredislibevent 应用程序连接到 Redis 服务器。

安装 libevent

libevent 主页 提供了下载该库所有版本的链接,但除非您需要针对特定版本,否则应使用最新版本。

下载 libevent 后,按照 README 文件中的说明编译并安装该库。

创建一个简单的应用程序

对于实际项目,您将使用 makefile 构建代码,但对于这个简单的测试,您可以将其放在一个名为 main.c 的文件中,并使用以下命令构建它(假设您使用 make install 安装了 libhiredislibevent 库)

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

请参阅 构建和安装 以了解如何构建 hiredis,如果您尚未这样做。

现在,将以下代码添加到 main.c 中。代码示例后有解释

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>

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

// Callback for the `GET` command. 
void getCallback(redisAsyncContext *c, void *r, void *privdata) {
    redisReply *reply = r;
    char *key = privdata;

    if (reply == NULL) {
        if (c->errstr) {
            printf("errstr: %s\n", c->errstr);
        }
        return;
    }

    printf("Key: %s, value: %s\n", key, reply->str);

    /* Disconnect after receiving the reply to GET */
    redisAsyncDisconnect(c);
}

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

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


int main (int argc, char **argv) {
#ifndef _WIN32
    signal(SIGPIPE, SIG_IGN);
#endif

    // Create the libevent `event_base` object to track all
    // events.
    struct event_base *base = event_base_new();

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

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

    // Use the Redis libevent adapter to attach the Redis connection
    // to the libevent main loop.
    redisLibeventAttach(c,base);
    
    redisAsyncSetConnectCallback(c, connectCallback);
    redisAsyncSetDisconnectCallback(c, disconnectCallback);
    
    char *key = "testkey";
    char *value = "testvalue";

    redisAsyncCommand(c, NULL, NULL, "SET %s %s", key, value);
    redisAsyncCommand(c, getCallback, key, "GET %s", key);
    
    // Run the event loop.
    event_base_dispatch(base);

    return 0;
}

该代码调用 event_base_new() 以初始化管理事件循环的核心 event_base 对象。然后,它创建一个到 Redis 的标准 异步连接,并使用 libevent 适配器函数 redisLibeventAttach() 将连接附加到事件循环。

设置 连接回调 后,该代码会发出两个异步 Redis 命令(有关更多信息,请参阅 构造异步命令)。最后一步是调用 event_base_dispatch() 以启动事件循环。这将等待命令被处理,然后在 getCallback() 函数中关闭 Redis 连接时退出。

运行代码

如果您编译并运行该代码,您将看到以下输出,表明回调已正确执行

Connected...
Key: testkey, value: testvalue
Disconnected...

您可以使用 KEYS 命令从 redis-cliRedis Insight 检查 "testkey" 字符串键是否已添加到 Redis 数据库。

为此页面评分
返回顶部 ↑