c语言操作hiredis 和libevent 实现发布和订阅的相关功能。

关于 c语言异步操作发布和订阅的问题。大概几以下几步

1 安装hiredis,https://github.com/redis/hiredis 进行下载安装,默认即可

2 安装redis,4.0版本以上。默认安装即可

3 安装libevent,2.2版本以上,与旧版本安装方法不太一样。

1
2
3
4
 $ mkdir build && cd build
 $ cmake ..    
 $ make
 $ make install

4 安装完libevent后,需要做个软连接,我这边是2.2版本的,默认安装到 /usr/local/lib/

1
2
3
 ln -s  /usr/local/lib/libevent.so  /usr/lib/libevent-2.2.so.1
 
 ldconfig    //让其马上生效

5 代码如下:

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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>

#include <hiredis.h>
#include <async.h>
#include <adapters/libevent.h>

void subCallback(redisAsyncContext *c, void *r, void *priv) {
    redisReply *reply = (redisReply*)r;
    if (reply == NULL) return;
    if ( reply->type == REDIS_REPLY_ARRAY && reply->elements == 3 ) {
        if ( strcmp( reply->element[0]->str, "subscribe" ) != 0 ) {
            printf( "Received[%s] channel %s: %s\n",
                    (char*)priv,
                    reply->element[1]->str,
                    reply->element[2]->str );
        }
    }
}

void connectCallback(const redisAsyncContext *c, int status) {
    if (status != REDIS_OK) {
        printf("Error: %s\n", c->errstr);
        return;
    }
    printf("Connected...\n");
}

void disconnectCallback(const redisAsyncContext *c, int status) {
    if (status != REDIS_OK) {
        printf("Error: %s\n", c->errstr);
        return;
    }
    printf("Disconnected...\n");
}

int main (int argc, char **argv) {
    signal(SIGPIPE, SIG_IGN);
    struct event_base *base = event_base_new();

    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);
    redisAsyncSetConnectCallback(c,connectCallback);
    redisAsyncSetDisconnectCallback(c,disconnectCallback);
    redisAsyncCommand(c, subCallback, (char*) "sub", "SUBSCRIBE deviceChannel");

    event_base_dispatch(base);

    return 0;
}

使用客户端命令进行发布deviceChannel频道消息

执行程序后:

完美!!