关于 c语言异步操作发布和订阅的问题。大概几以下几步
1 安装hiredis,https://github.com/redis/hiredis 进行下载安装,默认即可
2 安装redis,4.0版本以上。默认安装即可
3 安装libevent,2.2版本以上,与旧版本安装方法不太一样。
$ mkdir build && cd build
$ cmake ..
$ make
$ make install
4 安装完libevent后,需要做个软连接,我这边是2.2版本的,默认安装到 /usr/local/lib/
ln -s /usr/local/lib/libevent.so /usr/lib/libevent-2.2.so.1
ldconfig //让其马上生效
5 代码如下:
#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频道消息
执行程序后:
完美!!