A) 创建消息管理模块抽象类
在zinx/ziface下创建imsghandler.go文件。
package ziface/*消息管理抽象层*/type IMsgHandle interface{DoMsgHandler(request IRequest) //马上以非阻塞方式处理消息AddRouter(msgId uint32, router IRouter) //为消息添加具体的处理逻辑}
这里面有两个方法,AddRouter()就是添加一个msgId和一个路由关系到Apis中,那么DoMsgHandler()则是调用Router中具体Handle()等方法的接口。
B) 实现消息管理模块
在zinx/znet下创建msghandler.go文件。
package znetimport ("fmt""strconv""zinx/ziface")type MsgHandle struct{Apis map[uint32] ziface.IRouter //存放每个MsgId 所对应的处理方法的map属性}func NewMsgHandle() *MsgHandle {return &MsgHandle {Apis:make(map[uint32]ziface.IRouter),}}//马上以非阻塞方式处理消息func (mh *MsgHandle) DoMsgHandler(request ziface.IRequest) {handler, ok := mh.Apis[request.GetMsgID()]if !ok {fmt.Println("api msgId = ", request.GetMsgID(), " is not FOUND!")return}//执行对应处理方法handler.PreHandle(request)handler.Handle(request)handler.PostHandle(request)}//为消息添加具体的处理逻辑func (mh *MsgHandle) AddRouter(msgId uint32, router ziface.IRouter) {//1 判断当前msg绑定的API处理方法是否已经存在if _, ok := mh.Apis[msgId]; ok {panic("repeated api , msgId = " + strconv.Itoa(int(msgId)))}//2 添加msg与api的绑定关系mh.Apis[msgId] = routerfmt.Println("Add api msgId = ", msgId)}
