-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmessage_handler.go
More file actions
108 lines (93 loc) · 2.14 KB
/
Copy pathmessage_handler.go
File metadata and controls
108 lines (93 loc) · 2.14 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package danmu
import (
"encoding/json"
log "github.com/alecthomas/log4go"
"strconv"
"sync"
"time"
)
var (
commandChans map[*Room]chan string
lock *sync.RWMutex
pushFreq int
msgRoomObs RoomObserverInterface
)
func InitMessageHandler() error {
var err error
commandChans = make(map[*Room]chan string)
lock = &sync.RWMutex{}
pushFreq, err = strconv.Atoi(Conf.GetConfig("sys", "push_freq"))
msgRoomObs = new(MessageRoomObserver)
roomBucket.AttachObserver(msgRoomObs)
if err != nil {
return err
}
return OK
}
type MessageRoomObserver struct{}
func (mro *MessageRoomObserver) Update(action int, room *Room) {
lock.Lock()
defer lock.Unlock()
if action == RoomActionAdd {
commandChans[room] = make(chan string)
go messagePusher(room, commandChans[room])
} else if action == RoomActionDelete {
commandChans[room] <- "stop"
delete(commandChans, room)
}
}
func messageHandler() {
var (
proto *Proto
)
proto = NewProto()
for {
select {
case msg, ok := <-consumer.Messages():
if ok {
//fmt.Printf("%s/%d/%d\t%s\t%s\n", msg.Topic, msg.Partition, msg.Offset, msg.Key, msg.Value)
consumer.MarkOffset(msg, "") // mark message as processed
if err := json.Unmarshal(msg.Value, proto); err != nil {
log.Error(err)
continue
}
roomId := proto.RoomId
room, err := roomBucket.Get(rid(roomId))
if err != nil {
log.Error(err)
continue
}
room.protoList.PushBack(proto)
log.Debug(proto)
}
}
}
}
func messagePusher(room *Room, commandChan chan string) {
ticker := time.NewTicker(time.Duration(pushFreq) * time.Second) // 推送定时器
for {
select {
case command := <-commandChan:
if command == "stop" {
return
}
case <- ticker.C:
datas := room.protoList.PopAll()
protoLen := len(datas)
if protoLen > 0 {
protos := make([]*Proto, 0, protoLen)
for i := 0; i < protoLen; i++ {
proto, err := datas[i].(*Proto)
if err == false {
log.Error("*Proto type assertion failed")
continue
}
protos = append(protos, proto)
}
for _, client := range room.GetClients() {
client.BatchWrite(protos)
}
}
}
}
}