服务器多核模式

This commit is contained in:
kercylan98 2023-05-06 11:45:39 +08:00
parent 5e66a2df38
commit bac76884d9
2 changed files with 26 additions and 2 deletions

View File

@ -1,5 +1,10 @@
package server
import (
"go.uber.org/zap"
"minotaur/utils/log"
)
type Option func(srv *Server)
// WithProd 通过生产模式运行服务器
@ -17,3 +22,16 @@ func WithMessageBufferSize(size int) Option {
srv.messagePoolSize = size
}
}
// WithMultiCore 通过特定核心数量运行服务器,默认为单核
// - count > 1 的情况下,将会有对应数量的 goroutine 来处理消息
// - 注意HTTP和GRPC网络模式下不会生效
func WithMultiCore(count int) Option {
return func(srv *Server) {
srv.core = count
if srv.core < 1 {
log.Warn("WithMultiCore", zap.Int("count", count), zap.String("tips", "wrong core count configuration, corrected to 1, currently in single-core mode"))
srv.core = 1
}
}
}

View File

@ -26,6 +26,7 @@ func New(network Network, options ...Option) *Server {
event: &event{},
network: network,
options: options,
core: 1,
}
server.event.Server = server
@ -61,6 +62,7 @@ type Server struct {
initMessageChannel bool // 消息管道是否已经初始化
multiple bool // 是否为多服务器模式下运行
prod bool // 是否为生产模式
core int // 消息处理核心数
}
// Run 使用特定地址运行服务器
@ -103,8 +105,12 @@ func (slf *Server) Run(addr string) error {
if callback != nil {
go callback()
}
for message := range slf.messageChannel {
slf.dispatchMessage(message)
for i := 0; i < slf.core; i++ {
go func() {
for message := range slf.messageChannel {
slf.dispatchMessage(message)
}
}()
}
}