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

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

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

1)下载:

git clone https://github.com/redis/hiredis

2)进入hiredis文件夹  cd hiredis/

sudo make

sudo make install 

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

3 下载并安装libevent

1) 下载

选择一个版本进行下载,这里下载 2.1.11-stable

hiredis libev hiredis libevent发布_c语言

2)解压:

 sudo tar -zxvf libevent-2.1.11-stable.tar.gz 

3)解压后进入该目录 cd libevent-2.1.11-stable  执行如下命令

./configure

make                     // make 后生成的 .so 文件在 隐藏文件夹 .libs 中

sudo make install   //安装后默认安装在/usr/local/lib/ 目录下

4 安装完libevent后,默认安装到 /usr/local/lib/

1
2
3

 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频道消息

hiredis libev hiredis libevent发布_#include_02

 执行程序后:

hiredis libev hiredis libevent发布_c语言_03

完美!!