redis订阅发布

一、简介

Pub/Sub 从字面上理解就是发布(Publish)与订阅(Subscribe),在Redis中,你可以设定对某一个key值进行消息发布及消息订阅,当一个key值上进行了消息发布后,所有订阅它的客户端都会收到相应的消息。这一功能最明显的用法就是构建实时消息系统,比如普通的即时聊天,群聊等功能

二、demo

2.1 订阅具体key

  a连接上,订阅了 a1,a2,a3,三个key;

127.0.0.1:6379> SUBSCRIBE a1 a2 a3
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "a1"
3) (integer) 1
1) "subscribe"
2) "a2"
3) (integer) 2
1) "subscribe"
2) "a3"
3) (integer) 3
1) "message"
2) "a1"
3) "hello"
1) "message"
2) "a2"
3) "jacky"
1) "message"
2) "a3"
3) "aiai"

b连接,推送信息时,订阅的那端就能收到

127.0.0.1:6379> PUBLISH a1 hello
(integer) 1
127.0.0.1:6379> PUBLISH a2 jacky
(integer) 1
127.0.0.1:6379> PUBLISH a3 aiai
(integer) 1
127.0.0.1:6379> 

2.2 使用通配符来订阅

a连接, 订阅

[jacky@jacky bin]$ ./redis-cli -p 6379
127.0.0.1:6379> PSUBSCRIBE new*
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "new*"
3) (integer) 1
1) "pmessage"
2) "new*"
3) "new1"
4) "haha"
1) "pmessage"
2) "new*"
3) "new123"
4) "wohaishihaha"

b连接 发布

[jacky@jacky bin]$ ./redis-cli -p 6379
127.0.0.1:6379> PUBLISH new1 haha
(integer) 1
127.0.0.1:6379> PUBLISH new123 wohaishihaha
(integer) 1
127.0.0.1:6379> 

 

posted @ 2016-10-30 21:14  坏~牧羊人  阅读(209)  评论(0编辑  收藏  举报