《GO語言高級編程》設計中案例,僅作爲筆記進行收藏。發佈訂閱(publish-and-subscribe)模型通常被簡寫爲pub/sub模型。在這個模型中,消息⽣產者成爲發佈者(publisher),⽽消息消費者則成爲訂閱者(subscriber),⽣產者和消費者是M:N的關係。在
傳統⽣產者和消費者模型中,是將消息發送到⼀個隊列中,⽽發佈訂閱模型則是將消息發佈給⼀個主題。
- pubsub.go 發佈訂閱模型⽀持包
package pubsub
import (
"sync"
"time"
)
type (
// 訂閱者爲一個通道
subscriber chan interface{}
// 主題爲一個過濾器
topicFunc func(v interface{}) bool
)
// 發佈者對象
type Publisher struct {
m sync.RWMutex // 讀寫鎖
buffer int // 訂閱者隊列的緩存大小
timeout time.Duration // 發佈超時時間.
subscribers map[subscriber]topicFunc // 訂閱者信息
}
// 構建⼀個發佈者對象, 可以設置發佈超時時間和緩存隊列的長度
func NewPublisher(publishTimeout time.Duration, buffer int) *Publisher {
return &Publisher{
buffer: buffer,
timeout: publishTimeout,
subscribers: make(map[subscriber]topicFunc),
}
}
// 添加一個新的訂閱者,訂閱全部主題
func (p *Publisher) Subscribe() chan interface{} {
return p.SubscribeTopic(nil)
}
// 添加一個新的訂閱者,訂閱過濾器篩選後的主題
func (p *Publisher) SubscribeTopic(topic topicFunc) chan interface{} {
ch := make(chan interface{}, p.buffer)
p.m.Lock()
p.subscribers[ch] = topic
p.m.Unlock()
return ch
}
// 退出訂閱
func (p *Publisher) Evict(sub chan interface{}) {
p.m.Lock()
defer p.m.Unlock()
delete(p.subscribers, sub)
close(sub)
}
// 發佈一個主題
func (p *Publisher) Publish(v interface{}) {
p.m.RLock()
defer p.m.RUnlock()
var wg sync.WaitGroup
for sub, topic := range p.subscribers {
wg.Add(1)
go p.sendTopic(sub, topic, v, &wg)
}
wg.Wait()
}
// 關閉發佈者對象,同時關閉所有的訂閱者管道
func (p *Publisher) Close() {
p.m.Lock()
defer p.m.Unlock()
for sub := range p.subscribers {
delete(p.subscribers, sub)
close(sub)
}
}
// 發送主題,可以容忍一定的超時
func (p *Publisher) sendTopic(sub subscriber, topic topicFunc, v interface{}, wg *sync.WaitGroup) {
defer wg.Done()
if topic != nil && !topic(v) {
return
}
select {
case sub <- v:
case <-time.After(p.timeout):
}
}
- main.go 發佈訂閱實例
package main
import (
"fmt"
"strings"
"time"
"main/ch01/pubsub"
)
func main() {
p := pubsub.NewPublisher(100*time.Millisecond, 10)
defer p.Close()
all := p.Subscribe()
golang := p.SubscribeTopic(func(v interface{}) bool {
if s, ok := v.(string); ok {
return strings.Contains(s, "golang")
}
return false
})
p.Publish("hello, world!")
p.Publish("hello, golang!")
go func() {
for msg := range all {
fmt.Println("all:", msg)
}
}()
go func() {
for msg := range golang {
fmt.Println("golang:", msg)
}
}()
// 運行一定時間後退出
time.Sleep(3 * time.Second)
}