• hiredis发布/订阅示例


    [+]

    代码:

    1. #include <stdio.h>  
    2. #include <stdlib.h>  
    3. #include <string.h>  
    4. #include <signal.h>  
    5. #include "hiredis.h"  
    6. #include "async.h"  
    7. #include "adapters/libevent.h"  
    8.   
    9. void subCallback(redisAsyncContext *c, void *r, void *priv) {  
    10.     redisReply *reply = r;  
    11.     if (reply == NULL) return;  
    12.     if ( reply->type == REDIS_REPLY_ARRAY && reply->elements == 3 ) {  
    13.         if ( strcmp( reply->element[0]->str, "subscribe" ) != 0 ) {  
    14.             printf( "Received[%s] channel %s: %s ",  
    15.                     (char*)priv,  
    16.                     reply->element[1]->str,  
    17.                     reply->element[2]->str );  
    18.         }  
    19.     }  
    20. }  
    21.   
    22. void connectCallback(const redisAsyncContext *c, int status) {  
    23.     if (status != REDIS_OK) {  
    24.         printf("Error: %s ", c->errstr);  
    25.         return;  
    26.     }  
    27.     printf("Connected... ");  
    28. }  
    29.   
    30. void disconnectCallback(const redisAsyncContext *c, int status) {  
    31.     if (status != REDIS_OK) {  
    32.         printf("Error: %s ", c->errstr);  
    33.         return;  
    34.     }  
    35.     printf("Disconnected... ");  
    36. }  
    37.   
    38. int main (int argc, char **argv) {  
    39.     signal(SIGPIPE, SIG_IGN);  
    40.     struct event_base *base = event_base_new();  
    41.   
    42.     redisAsyncContext *c = redisAsyncConnect("127.0.0.1", 6379);  
    43.     if (c->err) {  
    44.         /* Let *c leak for now... */  
    45.         printf("Error: %s ", c->errstr);  
    46.         return 1;  
    47.     }  
    48.   
    49.     redisLibeventAttach(c,base);  
    50.     redisAsyncSetConnectCallback(c,connectCallback);  
    51.     redisAsyncSetDisconnectCallback(c,disconnectCallback);  
    52.     redisAsyncCommand(c, subCallback, (char*) "sub""SUBSCRIBE foo");  
    53.   
    54.     event_base_dispatch(base);  
    55.     return 0;  
    56. }  

    编译:

    gcc example-subpub.c libhiredis.a adapters/libevent.h -levent


    测试:

    订阅端

    ./a.out

    发布端

    ./redis-cli PUBLISH foo bar

  • 相关阅读:
    CSS基础
    bootbox api
    实现浏览器遗漏的原件 jQuery.selectCheckbox
    获取图片宽高方法
    javascript基础知识
    找工作总结
    cms配置使用
    页面被运营商加载广告
    iOS7 隐藏状态栏 hide statusBar
    Status Bar in iOS7
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13318293.html
Copyright © 2020-2023  润新知