feat: modular 包新增 Block 接口,当模块化服务实现 modular.Service 后可选择的实现 Block 接口,该接口将适用于具有阻塞等待需求的服务,例如网络服务器。

This commit is contained in:
kercylan98 2024-02-05 12:06:17 +08:00
parent a2695f4fcf
commit 3549fcca11
4 changed files with 56 additions and 0 deletions

10
modular/block.go Normal file
View File

@ -0,0 +1,10 @@
package modular
// Block 标识模块化服务为阻塞进程的服务,当实现了 Service 且实现了 Block 接口时,模块化应用程序会在 Service.OnMount 阶段完成后执行 OnBlock 函数
//
// 该接口适用于 Http 服务、WebSocket 服务等需要阻塞进程的服务。需要注意的是, OnBlock 的执行不能保证按照 Service 的注册顺序执行
type Block interface {
Service
// OnBlock 阻塞进程
OnBlock()
}

View File

@ -0,0 +1,28 @@
package server
import (
"github.com/kercylan98/minotaur/server"
"time"
)
type Service struct {
srv *server.Server
}
func (s *Service) OnInit() {
s.srv = server.New(server.NetworkNone, server.WithLimitLife(time.Second*3))
}
func (s *Service) OnPreload() {
}
func (s *Service) OnMount() {
}
func (s *Service) OnBlock() {
if err := s.srv.RunNone(); err != nil {
panic(err)
}
}

View File

@ -4,11 +4,13 @@ import (
"github.com/kercylan98/minotaur/modular"
"github.com/kercylan98/minotaur/modular/example/internal/service/services/attack"
"github.com/kercylan98/minotaur/modular/example/internal/service/services/login"
"github.com/kercylan98/minotaur/modular/example/internal/service/services/server"
)
func main() {
modular.RegisterServices(
new(attack.Service),
new(server.Service),
new(login.Service),
)
modular.Run()

View File

@ -4,6 +4,7 @@ import (
"fmt"
"github.com/kercylan98/minotaur/utils/log"
"reflect"
"sync"
)
var application *modular
@ -56,4 +57,19 @@ func Run() {
s := m.services[i]
s.instance.OnMount()
}
// OnBlock
var wait = new(sync.WaitGroup)
for i := 0; i < len(m.services); i++ {
s := m.services[i]
if block, ok := s.instance.(Block); ok {
wait.Add(1)
go func(wait *sync.WaitGroup) {
defer wait.Done()
block.OnBlock()
}(wait)
}
}
wait.Wait()
log.Info("all services exited")
}