1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
import (
"sync"
"time"
)
type HEvent struct {
Data interface{}
Topic string
}
type HEventData chan HEvent
type HEventDataArray []HEventData //一个topic 可以有多个消费者
type HEventBus struct {
sub map[string]HEventDataArray
rm sync.RWMutex
}
func HEventSrv() *HEventBus {
return h
}
func (h *HEventBus) Sub(topic string, ch HEventData) {
h.rm.Lock()
if chanEvent, ok := h.sub[topic]; ok {
h.sub[topic] = append(chanEvent, ch)
} else {
h.sub[topic] = append([]HEventData{}, ch)
}
defer h.rm.Unlock()
}
func (h *HEventBus) Push(topic string, data interface{}) {
h.rm.RLock()
defer h.rm.RUnlock()
if chanEvent, ok := h.sub[topic]; ok {
for _, ch := range chanEvent {
ch <- HEvent{
Data: data,
Topic: topic,
}
}
}
}
func (h *HEventBus) PushFullDrop(topic string, data interface{}) {
h.rm.RLock()
defer h.rm.RUnlock()
if chanEvent, ok := h.sub[topic]; ok {
for _, ch := range chanEvent {
select {
case ch <- HEvent{
Data: data,
Topic: topic,
}:
case <-time.After(time.Second):
}
}
}
}
|