rts-sim-testing-service/grpcproto/message.go

92 lines
1.7 KiB
Go
Raw Normal View History

2023-07-26 17:51:32 +08:00
package apiproto
import (
"time"
2023-07-31 08:41:42 +08:00
"go.uber.org/zap"
2023-07-26 17:51:32 +08:00
)
// 消息服务
type IMsgServer interface {
// 获取通道名
getChannelName() string
// 发送消息间隔时间,单位ms
getInterval() time.Duration
// 全量信息
2023-07-31 08:41:42 +08:00
allMsgData(params map[string]string) []byte
2023-07-26 17:51:32 +08:00
// 定时发送的消息
onTick() []TopicMsg
}
// 消息实体
type TopicMsg struct {
// 通道名称
channalName string
// 消息信息
data []byte
}
// 消息类型服务集合
var serverMap = make(map[string]*IMsgServer)
// 消息服务退出通道
var serverExitChannelMap = make(map[string]chan bool)
// 注册服务
func RegisterMsgServer(server IMsgServer) {
2023-07-31 08:41:42 +08:00
if client == nil {
InitClient()
}
2023-07-26 17:51:32 +08:00
serverMap[server.getChannelName()] = &server
if server.getInterval() > 0 {
exitChannel := make(chan bool)
serverExitChannelMap[server.getChannelName()] = exitChannel
2023-08-31 10:40:28 +08:00
tick := time.NewTicker(server.getInterval())
2023-07-26 17:51:32 +08:00
go func() {
defer func() {
if r := recover(); r != nil {
2023-07-31 08:41:42 +08:00
zap.S().Debug("定时器发生错误,%v\n", r)
2023-07-26 17:51:32 +08:00
}
}()
// 循环推送信息
for {
2023-08-31 10:40:28 +08:00
<-tick.C
topicMsgs := server.onTick()
2023-08-31 16:16:18 +08:00
if len(topicMsgs) == 0 {
continue
}
for _, msg := range topicMsgs {
PublishMsg(msg.channalName, msg.data)
}
select {
2023-07-26 17:51:32 +08:00
case <-exitChannel:
return
default:
2023-07-26 17:51:32 +08:00
}
}
}()
}
}
// 注销消息服务
func UnRegisterMsgServer(key string) {
channel := serverExitChannelMap[key]
if channel != nil {
// 定时任务取消
channel <- false
delete(serverExitChannelMap, key)
// 删除集合信息
delete(serverMap, key)
}
}
2023-07-31 08:41:42 +08:00
// 获取消息服务
func GetMsgServer(key string) *IMsgServer {
return serverMap[key]
}