gin_demo/event/dispatcher.go
2026-03-27 10:42:46 +08:00

42 lines
841 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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)
}
}