You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
67 lines
1.5 KiB
Go
67 lines
1.5 KiB
Go
2 years ago
|
package net
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"git.noahlan.cn/northlan/nnet/component"
|
||
|
"github.com/panjf2000/ants/v2"
|
||
|
)
|
||
|
|
||
|
type Handler struct {
|
||
|
allServices map[string]*component.Service // 所有注册的Service
|
||
|
allHandlers map[string]*component.Handler // 所有注册的Handler
|
||
|
|
||
|
workerSize int64 // 业务工作Worker数量
|
||
|
taskQueue []chan *Request // 工作协程的消息队列
|
||
|
}
|
||
|
|
||
|
func NewHandler() *Handler {
|
||
|
return &Handler{
|
||
|
allServices: make(map[string]*component.Service),
|
||
|
allHandlers: make(map[string]*component.Handler),
|
||
|
// TODO 读取配置
|
||
|
workerSize: 10,
|
||
|
taskQueue: make([]chan *Request, 10),
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (h *Handler) register(comp component.Component, opts []component.Option) error {
|
||
|
s := component.NewService(comp, opts)
|
||
|
|
||
|
p, _ := ants.NewPool()
|
||
|
p.Submit(func() {
|
||
|
|
||
|
})
|
||
|
|
||
|
if _, ok := h.allServices[s.Name]; ok {
|
||
|
return fmt.Errorf("handler: service already defined: %s", s.Name)
|
||
|
}
|
||
|
|
||
|
if err := s.ExtractHandler(); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
h.allServices[s.Name] = s
|
||
|
|
||
|
// 拷贝一份所有handlers
|
||
|
for name, handler := range s.Handlers {
|
||
|
handleName := fmt.Sprintf("%s.%s", s.Name, name)
|
||
|
// TODO print log
|
||
|
h.allHandlers[handleName] = handler
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
// DoWorker 将工作交给worker处理
|
||
|
func (h *Handler) DoWorker(request *Request) {
|
||
|
// 根据sessionID平均分配worker处理
|
||
|
workerId := request.Session.ID() % h.workerSize
|
||
|
fmt.Printf("sessionID %d to workerID %d\n", request.Session.ID(), workerId)
|
||
|
// 入队
|
||
|
h.taskQueue[workerId] <- request
|
||
|
}
|
||
|
|
||
|
func (h *Handler) handle(request *Request) {
|
||
|
|
||
|
}
|