还是直接上代码
原型见《GO高级编程》柴树杉 曹春晖著(1.6)
package main
import
(
"fmt"
"time"
"sync"
)
type (
subcriber chan interface{}
topicFunc func(v interface{}) bool
)
// 发布者结构体
type Publisher struct {
m sync.RWMutex //增加订阅者,线程间互斥
buffer int32 //订阅者信道缓冲
timeout time.Duration //等待超时,当订阅者信道缓冲满后超时
subscribers map[subcriber]topicFunc //存储订阅者,和订阅者的过滤函数
}
// 构建一个发布者
func NewPiblisher(publishTimeout time.Duration, buffer int32) *Publisher{
return &Publisher{
buffer: buffer,
timeout: publishTimeout,
subscribers: make(map[subcriber]topicFunc),
}
}
// 订阅全部信息
func (p *Publisher) Subscribe() subcriber{
return p.SubscribeTopic(nil)
}
// 订阅信息,按着入参过滤
func (p *Publisher) SubscribeTopic(topic topicFunc) subcriber{
ch := make(subcriber, p.buffer)
p.m.Lock()
defer p.m.Unlock()
p.subscribers[ch] = topic
return ch
}
// 某一个订阅者退出
func (p *Publisher) SubQuit(sub subcriber) {
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 func(sub subcriber, ftopic topicFunc){
defer wg.Done()
if topic!=nil && !topic(v) {
return
}
select {
case sub<-v:
case <-time.After(p.timeout):
fmt.Println("订阅者么有取数据导致信道堵塞...")
}
}(sub, topic)
}
wg.Wait()
}
func main(){
p := NewPiblisher(time.Second, 2)
all := p.Subscribe()
str := p.SubscribeTopic(func(v interface{}) bool{
if _,ok := v.(string); ok {
return true
}
return false
})
p.Publish("hello")
p.Publish("hello")
p.Publish("hello")
go func(){
for msg:= range all{
fmt.Println("all: ",msg)
}
}()
go func(){
for msg:= range str{
fmt.Println("str: ",msg)
}
}()
time.Sleep(10* time.Second)
fmt.Println("hello world")
}