I want get as much as possible from Redis + Hiredis + libevent.
I'm using following code (without any checks to be short)
#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;
redisAsyncContext* c;
void get_cb(redisAsyncContext* context, void* r, void* data) {
redisReply* reply = r;
struct reqData* rd = data;
evbuffer_add_printf(rd->buf, "%s", reply->str);
evhttp_send_reply(rd->req, HTTP_OK, NULL, rd->buf);
evbuffer_free(rd->buf);
redisAsyncDisconnect(context);
}
void cb(struct evhttp_request* req, void* args) {
struct evbuffer* buf;
buf = evbuffer_new();
reqData* rd = malloc(sizeof(reqData));
rd->req = req;
rd->buf = buf;
c = redisAsyncConnect("0.0.0.0", 6380);
redisLibeventAttach(c, base);
redisAsyncCommand(c, get_cb, rd, "GET name");
}
int main(int argc, char** argv) {
struct evhttp* http;
struct evhttp_bound_socket* sock;
base = event_base_new();
http = evhttp_new(base);
sock = evhttp_bind_socket_with_handle(http, "0.0.0.0", 8080);
evhttp_set_gencb(http, cb, NULL);
event_base_dispatch(base);
evhttp_free(http);
event_base_free(base);
return 0;
}
To compile, use gcc -o main -levent -lhiredis main.c
assuming libevent, redis and hiredis in system.
I curious when I need to do redisAsyncConnect
? In main()
once or (as example shows) in every callback. Is there anything I can do to boost performance?
I'm getting about 6000-7000 req/s. Using ab
to benchmark this, stuff complicates when trying big numbers (e.g. 10k reqs) - it cannot complete benchmark and freezes. Doing the same thing but in blocking way the results are 5000-6000 req/s.
I've extended max file open by limit -n 10000
. I'm using Mac OS X Lion.