redis使用(五):c非同步介面__redis

來源:互聯網
上載者:User

hredis提供了,非同步介面,而且可以結合libevent、libev等訊息架構使用;

範例程式碼(結合libevent使用,libevent參考):

test_asyn.c

#include<stdio.h>#include<stdlib.h>#include<string.h>#include<hiredis/hiredis.h>#include<hiredis/async.h>#include<hiredis/adapters/libevent.h>#include<event2/event.h>//設定get命令的回呼函數void getCallback(redisAsyncContext *c, void *r, void *privdata) {  printf("in get cmd callback \n");  redisReply *reply = r;  if (reply == NULL){      printf("reply == NULL");      return;  }  printf("get cmd:[%s], reply->str:%s\n", (char*)privdata, reply->str);  // Disconnect   redisAsyncDisconnect(c);}//設定串連回呼函數void connectCallback(const redisAsyncContext *c, int status) {  if (status != REDIS_OK) {    printf("in connectCallback Error: %s\n", c->errstr);    return;  }  printf("Connected...\n");}//設定中斷連線回呼函數void disconnectCallback(const redisAsyncContext *c, int status) {  if (status != REDIS_OK) {    printf("in disconnectCallback  Error: %s\n", c->errstr);    return;  }  printf("Disconnected...\n");}int main (int argc, char **argv) {  struct event_base *base = event_base_new();//建立一個libevent事件處理  redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);//建立非同步串連  if (c->err) {    /* Let *c leak for now... */    printf("Error: %s\n", c->errstr);    return 1;  }  redisLibeventAttach(c,base);//將串連添加到libevent事件處理  redisAsyncSetConnectCallback(c,connectCallback);//設定串連回調  redisAsyncSetDisconnectCallback(c,disconnectCallback);//設定中斷連線回調  redisAsyncCommand(c, NULL, NULL, "SET aaa %b", "bbb", sizeof("bbb"));//發送set命令  redisAsyncCommand(c, getCallback, (char*)"GET aaa", "GET aaa");//發送get命令  event_base_dispatch(base); //開始libevent迴圈。注意在這一步之前redis是不會進行串連的  return 0;}

Makefile

all:test_asyn.c     gcc -o test_asyn test_asyn.c -I/mydir/local/include  -I/mydir/include -L/mydir/local/lib -lhiredis  -L/mydir/lib -levent

執行結果(需要先把/mydir/local/lib和/mydir/lib加入到LD_LIBRARY_PATH):

$ ./test_asyn Connected...in get cmd callback get cmd:[GET aaa], reply->str:bbbDisconnected...
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.