42 lines
841 B
Go
42 lines
841 B
Go
package event
|
||
|
||
import "sync"
|
||
|
||
// Dispatcher 是进程内轻量事件总线(内存版)。
|
||
// 对于 request/reply 事件,Publish 会同步调用订阅者,
|
||
// 因此调用方可直接从 Reply 通道等待结果。
|
||
type Dispatcher struct {
|
||
mu sync.RWMutex
|
||
subs map[string][]func(Event)
|
||
}
|
||
|
||
func NewDispatcher() *Dispatcher {
|
||
return &Dispatcher{
|
||
subs: make(map[string][]func(Event)),
|
||
}
|
||
}
|
||
|
||
func (d *Dispatcher) Subscribe(eventType string, handler func(Event)) {
|
||
if eventType == "" || handler == nil {
|
||
return
|
||
}
|
||
d.mu.Lock()
|
||
defer d.mu.Unlock()
|
||
d.subs[eventType] = append(d.subs[eventType], handler)
|
||
}
|
||
|
||
func (d *Dispatcher) Publish(e Event) {
|
||
if e == nil {
|
||
return
|
||
}
|
||
eventType := e.Type()
|
||
|
||
d.mu.RLock()
|
||
handlers := append([]func(Event){}, d.subs[eventType]...)
|
||
d.mu.RUnlock()
|
||
|
||
for _, h := range handlers {
|
||
h(e)
|
||
}
|
||
}
|