gpt4 book ai didi

asynchronous - redisAsyncContext 中的 ev

转载 作者:可可西里 更新时间:2023-11-01 11:25:57 26 4
gpt4 key购买 nike

在redis Async Context中,定义了struct ev:

struct {  
void *data;
void (*addRead)(void *privdata);
void (*delRead)(void *privdata);
void (*addWrite)(void *privdata);
void (*delWrite)(void *privdata);
void (*cleanup)(void *privdata);
} ev;

有一个函数:

void CleanUpEvent()
{
if (m_pstContext->ev.delRead)
{
m_pstContext->ev.delRead(m_pstContext->ev.data);
}

if (m_pstContext->ev.delWrite)
{
m_pstContext->ev.delWrite(m_pstContext->ev.data);
}
}

它是如何工作的?我什么时候应该使用 ev?

最佳答案

基本上你只需要提供连接和断开回调,hiredis 会为你做其他事情。

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

void connectCallback(const redisAsyncContext *c, int status);
void disconnectCallback(const redisAsyncContext *c, int status);
void getCallback(redisAsyncContext *c, void *r, void *privdata);

int main (int argc, char **argv) {

//make a async context
redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);
if (c->err) {
/* Let *c leak for now... */
printf("Error: %s\n", c->errstr);
return 1;
}

//now, you need to attach hiredis to your event loop, its depends on event lib that you are using
//example for libuv
redisLibuvAttach(c, uv_default_loop());

//now we setup callbacks
redisAsyncSetConnectCallback(c, connectCallback);
redisAsyncSetDisconnectCallback(c, disconnectCallback);

//enquee "SET foo bar" without callback
redisAsyncCommand(c, NULL, NULL, "SET foo %b", "bar", strlen("bar"));

//enquee "GET foo" with callback and privdata "end-1"
redisAsyncCommand(c, getCallback, (char*)"end-1", "GET foo");

//run your event loop
uv_run(loop, UV_RUN_DEFAULT);

return 0;
}

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");
}

void getCallback(redisAsyncContext *c, void *r, void *privdata) {
redisReply *reply = r;
if (reply == NULL) return;
printf("argv[%s]: %s\n", (char*)privdata, reply->str);

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

检查 https://github.com/redis/hiredis/tree/master/examples有关不同事件库的更多示例。

关于asynchronous - redisAsyncContext 中的 ev,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45346630/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com