go_dreamfactory/modules/gateway/queue_comp.go
2023-09-04 15:52:47 +08:00

109 lines
2.5 KiB
Go

package gateway
import (
"go_dreamfactory/lego/core"
"go_dreamfactory/lego/core/cbase"
"go_dreamfactory/lego/sys/log"
"go_dreamfactory/pb"
"sync"
"time"
"google.golang.org/protobuf/proto"
)
type UserLoginData struct {
sessionId string
Account string //账号
loginreq *pb.UserMessage //登录请求
}
/*
登录排队组件
*/
type QueueComp struct {
cbase.ModuleCompBase
options *Options
module *Gateway // 网关
lock sync.RWMutex
loginQueue []*UserLoginData //登录队列
}
func (this *QueueComp) Init(service core.IService, module core.IModule, comp core.IModuleComp, options core.IModuleOptions) (err error) {
err = this.ModuleCompBase.Init(service, module, comp, options)
this.options = options.(*Options)
this.module = module.(*Gateway)
this.loginQueue = make([]*UserLoginData, 0, 2000)
return
}
func (this *QueueComp) Start() (err error) {
err = this.ModuleCompBase.Start()
go this.run()
return
}
func (this *QueueComp) inLoginQueue(sessionId string, req *pb.UserMessage) (index int32, err error) {
var (
msg proto.Message
loginreq *pb.UserLoginReq
)
if msg, err = req.Data.UnmarshalNew(); err != nil {
log.Errorf("[Handle Api] UserMessage:user.login Unmarshal err:%v", err)
return
}
loginreq = msg.(*pb.UserLoginReq)
this.lock.Lock()
this.loginQueue = append(this.loginQueue, &UserLoginData{
sessionId: sessionId,
Account: loginreq.Account,
loginreq: &pb.UserMessage{
MsgId: req.MsgId,
MainType: req.MainType,
SubType: req.SubType,
Data: req.Data,
ServicePath: req.ServicePath,
},
})
index = int32(len(this.loginQueue))
this.lock.Unlock()
return
}
func (this *QueueComp) run() {
var (
loginreq *UserLoginData
agent IAgent
err error
num int
sessionIds []string = make([]string, 0)
)
for {
sessionIds = sessionIds[:0]
this.lock.Lock()
num = len(this.loginQueue)
if num > 0 {
loginreq = this.loginQueue[0]
this.loginQueue = this.loginQueue[1:]
for _, v := range this.loginQueue {
sessionIds = append(sessionIds, v.sessionId)
}
}
this.lock.Unlock()
if num == 0 {
time.Sleep(time.Second * 1)
continue
}
agent = this.module.agentMgr.getAgent(loginreq.sessionId)
if agent != nil && agent.UserId() == "" { //未登录
if err = agent.HandleMessage(loginreq.loginreq); err != nil { //登录失败处理
}
} else { //离线处理
}
if len(sessionIds) > 0 {
this.module.agentMgr.QueueChange(sessionIds)
}
}
}