Redis

redis发布订阅c hiredis发布/订阅示例

阅读 1598

收藏 8

点赞 1

发布订阅(pub/sub)是一种消息通信模式,主要的目的是解耦消息发布者和消息订阅者之间的耦合,这点和设计模式中的观察者模式比较相似。pub /sub不仅仅解决发布者和订阅者直接代码级别耦合也解决两者在物理部署上的耦合。redis作为一个pub/sub server,在订阅者和发布者之间起到了消息路由的功能。订阅者可以通过subscribe和psubscribe命令向redis server订阅自己感兴趣的消息类型,redis将消息类型称为通道(channel)。当发布者通过publish命令向redis server发送特定类型的消息时。订阅该消息类型的全部client都会收到此消息。这里消息的传递是多对多的。一个client可以订阅多个 channel,也可以向多个channel发送消息。

#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
=
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 foo
"
); event_base_dispatch(
base
);
return
0
; }