public
Created

Example of async hiredis with libevent

  • Download Gist
mytest.c
C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
/*
Based on code provided by Sebastian Sito in stackoverflow question:
http://stackoverflow.com/questions/9958589/async-redis-pooling-using-lib-event
*/
 
#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);
 
evbuffer_free(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);
evbuffer_free(buf);
return;
*/
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("0.0.0.0", 6379);
/* error handling omitted for brevity sake */
 
base = event_base_new();
http = evhttp_new(base);
sock = evhttp_bind_socket_with_handle(http, "0.0.0.0", 8080);
redisLibeventAttach(c, base);
evhttp_set_gencb(http, cb, c);
 
event_base_dispatch(base);
 
/* Redis disconnection code omitted */
 
evhttp_free(http);
event_base_free(base);
return 0;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.