Create a gist now

Instantly share code, notes, and snippets.

Example of async hiredis with libevent
Based on code provided by Sebastian Sito in stackoverflow question:
#include <stdlib.h>
#include <event2/event.h>
#include <event2/http.h>
#include <event2/buffer.h>
#include <hiredis/hiredis.h>
#include <hiredis/async.h>
#include <hiredis/adapters/libevent.h>
typedef struct reqData {
struct evhttp_request* req;
struct evbuffer* buf;
} reqData;
struct event_base* base;
void get_cb(redisAsyncContext* context, void* r, void* data) {
redisReply* reply = r;
struct reqData* rd = data;
/* error handling omitted for brevity sake */
evbuffer_add_printf(rd->buf, "%s\n", reply->str);
evhttp_send_reply(rd->req, HTTP_OK, NULL, rd->buf);
free( rd );
void cb(struct evhttp_request* req, void* args) {
struct evbuffer* buf;
redisAsyncContext* c = (redisAsyncContext *) args;
buf = evbuffer_new();
/* Uncomment following code to test without any Redis call
evbuffer_add_printf(buf, "toto\n");
evhttp_send_reply(req, HTTP_OK, NULL, buf);
reqData* rd = malloc(sizeof(reqData));
rd->req = req;
rd->buf = buf;
redisAsyncCommand(c, get_cb, rd, "GET name");
int main(int argc, char** argv) {
struct evhttp* http;
struct evhttp_bound_socket* sock;
/* Redis connection to be declared and attached to the event loop */
redisAsyncContext* c;
c = redisAsyncConnect("", 6379);
/* error handling omitted for brevity sake */
base = event_base_new();
http = evhttp_new(base);
sock = evhttp_bind_socket_with_handle(http, "", 8080);
redisLibeventAttach(c, base);
evhttp_set_gencb(http, cb, c);
/* Redis disconnection code omitted */
return 0;

This comment has been minimized.

Show comment
Hide comment

diorahman May 12, 2017

In here the redisAsync has its own "loop". Can we reuse the loop provided by the base?

In here the redisAsync has its own "loop". Can we reuse the loop provided by the base?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment