Redis的发布订阅
Redis 发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息。
Redis 客户端可以订阅任意数量的频道。
订阅/发布消息图:
命令
这些命令被广泛用于构建即时通信应用,比如网络聊天室(chatroom)he 实时广播,实时提醒等。
测试
订阅端
127.0.0.1:6379> SUBSCRIBE haiyang #订阅一个频道 haiyang
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "haiyang"
3) (integer) 1
#等待读取推送的消息
1) "message" # 消息
2) "haiyang" # 哪个频道的消息
3) "hello haiyang" # 消息内容
1) "message"
2) "haiyang"
3) "hello redis"
发送端
[root@localhost bin]# redis-cli -p 6379
127.0.0.1:6379> ping
PONG
127.0.0.1:6379> PUBLISH haiyang "hello haiyang" #发布者发布消息到频道
(integer) 1
127.0.0.1:6379> PUBLISH haiyang "hello redis" #发布者发布消息到频道
(integer) 1
127.0.0.1:6379>