Skip to content

Instantly share code, notes, and snippets.

@cuber
Created August 20, 2015 11:11
Show Gist options
  • Save cuber/abf20efe4c1b99950fc7 to your computer and use it in GitHub Desktop.
Save cuber/abf20efe4c1b99950fc7 to your computer and use it in GitHub Desktop.
Async persist connection control
//
// main.c
// redisd
//
// Created by Cube on 15/8/19.
// Copyright (c) 2015年 cube. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <event2/event.h>
#include <hiredis/hiredis.h>
#include <hiredis/async.h>
#include <hiredis/adapters/libevent.h>
struct Ctx {
int freed;
struct event_base * eb;
redisAsyncContext * ac;
};
void rds_cb(struct redisAsyncContext * ac, void * reply, void * ptr)
{
redisReply * r = reply;
if (ac->err) {
// printf("redis: %s %s\n", __FUNCTION__, ac->errstr);
} else if (!r) {
printf("reply: NULL\n");
} else if (r->type == REDIS_REPLY_ERROR) {
printf("reply: %s\n", r->str);
} else {
// everything is ok
}
}
void rds_ifree_cb(const struct redisAsyncContext * ac, int err)
{
struct Ctx * ctx = ac->data;
if (err) {
ctx->freed = 1;
printf("redis: freed: %s\n", ac->errstr);
}
}
void rds_connect(struct Ctx * ctx)
{
if (!ctx->freed) return;
// do connect
ctx->ac = redisAsyncConnect("192.168.44.67", 6379);
ctx->ac->data = ctx;
ctx->freed = 0;
redisAsyncSetConnectCallback (ctx->ac, rds_ifree_cb);
redisAsyncSetDisconnectCallback(ctx->ac, rds_ifree_cb);
redisLibeventAttach (ctx->ac, ctx->eb);
}
void evt_cb(int fd, short which, void * ptr)
{
struct Ctx * ctx = ptr;
// do connect
rds_connect(ctx);
// do send command
redisAsyncCommand(ctx->ac, rds_cb, ctx, "set %s %d", "hello", 123);
}
int main(int argc, const char * argv[])
{
signal(SIGPIPE, SIG_IGN);
struct Ctx * ctx = malloc(sizeof(struct Ctx));
ctx->eb = event_base_new();
ctx->ac = NULL;
ctx->freed = 1;
struct timeval tv = {0, 100};
struct event * e = event_new(ctx->eb, -1, EV_PERSIST | EV_TIMEOUT, evt_cb, ctx);
event_add(e, &tv);
event_base_loop(ctx->eb, 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment