go_dreamfactory/modules/chat/sysnotice_comp.go
2023-12-21 11:04:31 +08:00

91 lines
1.7 KiB
Go

package chat
import (
"context"
"go_dreamfactory/comm"
"go_dreamfactory/lego/core"
"go_dreamfactory/lego/core/cbase"
"go_dreamfactory/pb"
"sync"
"time"
)
//系统公告维护组件
type sysnoticeComp struct {
cbase.ModuleCompBase
module *Chat
msgs []*pb.DBChat
lock sync.RWMutex
max int
}
// 组件初始化接口
func (this *sysnoticeComp) Init(service core.IService, module core.IModule, comp core.IModuleComp, opt core.IModuleOptions) (err error) {
this.ModuleCompBase.Init(service, module, comp, opt)
this.module = module.(*Chat)
this.msgs = make([]*pb.DBChat, 0, 10)
this.max = 10
return
}
func (this *sysnoticeComp) Start() (err error) {
this.ModuleCompBase.Start()
go this.run()
return
}
//上传系统消息
func (this *sysnoticeComp) pushsysmsg(msg *pb.DBChat) bool {
var ok bool
this.lock.Lock()
if count := len(this.msgs); count < this.max {
this.msgs = append(this.msgs, msg)
ok = true
}
this.lock.Unlock()
return ok
}
func (this *sysnoticeComp) run() {
timer := time.NewTicker(time.Second * 2)
for {
select {
case <-timer.C:
this.broadcastmsg()
}
}
}
func (this *sysnoticeComp) broadcastmsg() {
var (
msg *pb.DBChat
err error
)
this.lock.Lock()
if len(this.msgs) > 0 {
msg = this.msgs[0]
this.msgs = this.msgs[1:]
}
this.lock.Unlock()
if msg != nil {
if this.module.IsCross() {
if err = this.module.modelChat.sendChatToSystem(msg); err != nil {
this.module.Errorln(err)
return
}
} else {
if _, err = this.module.service.AcrossClusterRpcGo(
context.Background(),
this.module.GetCrossTag(),
comm.Service_Worker,
string(comm.Rpc_ModuleChatPushChat),
msg,
nil); err != nil {
this.module.Errorln(err)
return
}
}
}
}