Skip to content

Commit 688a2dd

Browse files
committed
event 事件
1 parent 600b6a4 commit 688a2dd

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed

hevent/event.go

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package hevent
2+
3+
import "sync"
4+
5+
type HEvent struct {
6+
Data interface{}
7+
Topic string
8+
}
9+
10+
type HEventData chan HEvent
11+
type HEventDataArray []HEventData //一个topic 可以有多个消费者
12+
13+
type HEventBus struct {
14+
sub map[string]HEventDataArray
15+
rm sync.RWMutex
16+
}
17+
18+
var h *HEventBus
19+
20+
func init() {
21+
h = &HEventBus{
22+
sub: make(map[string]HEventDataArray),
23+
}
24+
}
25+
26+
type HEventRepo interface {
27+
Sub(topic string, ch HEventData)
28+
Push(topic string, data interface{})
29+
}
30+
31+
func HEventSrv() *HEventBus {
32+
return h
33+
}
34+
35+
func (h *HEventBus) Sub(topic string, ch HEventData) {
36+
h.rm.Lock()
37+
if chanEvent, ok := h.sub[topic]; ok {
38+
h.sub[topic] = append(chanEvent, ch)
39+
} else {
40+
h.sub[topic] = append([]HEventData{}, ch)
41+
}
42+
defer h.rm.Unlock()
43+
}
44+
45+
func (h *HEventBus) Push(topic string, data interface{}) {
46+
h.rm.RLock()
47+
defer h.rm.RUnlock()
48+
if chanEvent, ok := h.sub[topic]; ok {
49+
for _, ch := range chanEvent {
50+
ch <- HEvent{
51+
Data: data,
52+
Topic: topic,
53+
}
54+
}
55+
}
56+
}

hevent/event_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package hevent
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
"time"
7+
)
8+
9+
func TestName(t *testing.T) {
10+
var ch = make(chan HEvent, 10)
11+
HEventSrv().Sub("hw", ch)
12+
//go GetHEventSrv().Push("topic1", "Hi topic 1")
13+
go func() {
14+
for {
15+
time.Sleep(1000 * time.Second)
16+
HEventSrv().Push("hw", "Hi topic 1")
17+
}
18+
}()
19+
for {
20+
fmt.Println(<-ch)
21+
}
22+
}

0 commit comments

Comments
 (0)