-
Notifications
You must be signed in to change notification settings - Fork 31
添加一个服务节点
Chenghui edited this page Apr 13, 2020
·
1 revision
添加一个后端节点,主要提供游戏的逻辑业务。取名叫user。
- 首先,添加配置,在bin/conf/servers.json中添加:
"user":{
"user-1":{"id":"user-1", "host":"127.0.0.1", "port":5070}
},
2.代码中,定义一个UserServer类型,继承服务基类app.ServerDefault,如下(在app/user/userServer.go):
type UserServer struct {
*app.ServerDefault
msgHandler *MsgHandler
}
- 每个节点都要实现app.Server接口:
type Server interface {
OnStart()
Run(closeSig chan bool)
OnStop()
}
这样,我们添加如下代码实现这些接口:
func (g *UserServer) OnStart(){
}
func (g *UserServer) Run(closeSig chan bool){
for _,com := range g.Components {
go com.Run(closeSig)
}
<-closeSig
//closing
log.Info("gate closing")
}
func (g *UserServer) OnStop(){
for _,com := range g.Components {
com.OnDestroy()
}
}
- 我们开始加载组件,如果这个节点只提供服务,不需要调用其它节点的服务,只需要添加remote组件,在onStart中添加组件:
settings, err := config.ServersConfig.GetMap("user")
if err != nil {
log.Error("%s", err)
}
serverSetting := settings[g.ServerId].(map[string]interface{})
remoteAddr := fmt.Sprintf("%s:%.f",serverSetting["host"], serverSetting["port"])
remote := rpcServer.NewRemote(
rpcServer.Addr(remoteAddr),
rpcServer.RegistryType(config.RegistryConfig.String("registry")),
rpcServer.RegistryAddr(config.RegistryConfig.String("addr")),
rpcServer.BasePath(config.RegistryConfig.String("basePath")))
g.Components["remote"] = remote
g.msgHandler = &MsgHandler{r:remote} //消息处理器
- 添加一个Hello服务类,这个类只提供一个“Hello.Say"服务。
type HelloReq struct {
Route string
Words string
}
type HelloResp struct {
Words string
}
type Hello struct {
}
func (h *Hello) Say(ctx context.Context, args *rpc.Args, replay *HelloResp) error {
var req HelloReq
args.GetObject(&req)
//log.Info("hello" + req.Words)
replay.Words = "hello " + req.Words
return nil
}
- 注册Hello服务
func init() {
RegisterHandler(new(Hello))
msgService.GetMsgService().Register("Hello.Say", &HelloReq{}, &HelloResp{})
}
- 服务添加完成了,客户端测试一下:
pomelo_request("Hello.Say", {Words:"kudoo"}, function(data) {
})