在应用级其做用是为了减小依赖关系,一般也叫观察者模式。主要是把耦合点单独抽离出来做为第三方,隔离易变化的发送方和接收方。前端
发送方:只负责向第三方发送消息。(杂志社把读者杂志交给邮局) 接收方:被动接收消息。(1:向邮局订阅读者杂志,2:门口去接邮过来的杂志) 第三方做用是:存储订阅杂志的接收方,并在杂志过来时送给接收方。 (邮局)git
示例,发送方把杂志放到邮局里面:github
if (QA.AddBug()) EmailNotify();
接收方到邮局登记地址,有杂志过来时送货上门:redis
EmailNotify += () => { Console.WriteLine("A君"); }; EmailNotify += () => { Console.WriteLine("B君"); };
第三方邮局接受读者杂志订阅,收到杂志时进行派送:编程
public delegate void MessageHandler(); public static event MessageHandler EmailNotify; if (QA.AddBug()) EmailNotify();
当咱们把观察者模式放大到系统级时,就是发布订阅(pub/sub)了。 主要是用来下降发布者和订阅者的耦合,提升前端系统吞吐量。结构如图:服务器
Redis实现完整的发布订阅范式,就是说任何一台redis服务器,启动后均可以当作发布订阅服务器。工具
启动订阅者client。ui
redis-cli.exe -h 127.0.0.1 -p 6379
订阅bar频道。格式:SUBSCRIBE name1 name2。 成功订阅回复,分别对应订阅类型、订阅频道、订阅数量。code
127.0.0.1:6379> SUBSCRIBE bar Reading messages... (press Ctrl-C to quit) 1) "subscribe" 2) "bar" 3) (integer) 1
新起个发布者client,发送消息。格式:publish channelName Message。blog
127.0.0.1:6379> publish bar val (integer) 1
订阅client回复,分别对应消息类型,频道,消息。
1) "message" 2) "bar" 3) "val"
图例
Redis支持模式匹配订阅,*为模糊匹配符。 订阅全部频道的消息
PSUBSCRIBE *
订阅以news.开头的全部频道。
PSUBSCRIBE news.*
取消普通订阅和取消模式订阅的命令。
UNSUBSCRIBE bar PUNSUBSCRIBE ba*
取消在官方提供的链接工具中没法模拟的。
查看订阅消息是redis在2.8中心增长的命令之一。
返回当前服务器被订阅的全部频道。
127.0.0.1:6379> pubsub channels 1) "bar"
指定匹配参数,返回与模式匹配的全部频道。
127.0.0.1:6379> pubsub channels ba* 1) "bar"
接受任意多个频道做为输入参数,返回这些频道的订阅者数量。
127.0.0.1:6379> pubsub numsub bar bar2 1) "bar" 2) (integer) 1 3) "bar2" 4) (integer) 0
RedisPubSub client = new RedisPubSub("127.0.0.1", 6381); client.OnUnSubscribe += (obj) => { Console.WriteLine(); }; client.OnMessage = (sender, arcgs) =>{ Console.WriteLine(arcgs); }; client.OnError = (Exception) => { Console.WriteLine(Exception.Message); }; client.Subscribe("bar"); Console.ReadLine();
using (RedisClient client = new RedisClient("127.0.0.1", 6381)) { client.Set("key", "value"); client.Get("key"); }
PoolRedisClient prc = new PoolRedisClient(new PoolConfiguration()); prc.Single.Set("key", "value"); prc.Single.Get("key");