作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
在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/
在redis Async Context中,定义了struct ev: struct { void *data; void (*addRead)(void *privdata);
我是一名优秀的程序员,十分优秀!