package backend import ( "context" "net/http" "server/call" "server/config" "server/db" edb "server/db/es" mdb "server/db/mysql" rdb "server/db/redis" "server/modules/backend/bdb" "server/modules/backend/routers" "time" "github.com/liangdas/mqant/conf" "github.com/liangdas/mqant/log" "github.com/liangdas/mqant/module" basemodule "github.com/liangdas/mqant/module/base" ) var ( Module = func() module.Module { this := new(Backend) return this } BackDB = new(mdb.MysqlClient) ) type Backend struct { basemodule.BaseModule httpSvr *http.Server addr string } func (b *Backend) GetType() string { //很关键,需要与配置文件中的Module配置对应 return "backend" } func (b *Backend) Version() string { //可以在监控时了解代码版本 return "1.0.0" } func (b *Backend) OnInit(app module.App, settings *conf.ModuleSettings) { b.BaseModule.OnInit(b, app, settings) call.NewCaller(b) db.InitDB(&mdb.MysqlClient{}, &rdb.RedisClient{}, &edb.EsClient{}) bdb.InitMysql() // 自动初始化后台数据库 bdb.MigrateDB() // 自动初始化游戏服数据库 MigrateDB() b.addr = config.GetConfig().Backend.Addr call.InitReload(b.App.Transport()) // 开启定时查询 StartTimer() loadConfig() } func (b *Backend) startHttpServer() { router := routers.SetUpRouter() srv := &http.Server{ Addr: b.addr, Handler: router, } go func() { if err := srv.ListenAndServe(); err != nil { panic(err) } }() // returning reference so caller can call Shutdown() b.httpSvr = srv } func (b *Backend) Run(closeSig chan bool) { log.Info("backend: starting HTTP server :%s", b.addr) call.InitTimeWheel(closeSig) call.InitWarn(b.App.Transport()) b.startHttpServer() <-closeSig log.Info("backend: stopping HTTP server") } func (b *Backend) OnDestroy() { // The context is used to inform the server it has 5 seconds to finish // the request it is currently handling ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() // now close the server gracefully ("shutdown") // timeout could be given instead of nil as a https://golang.org/pkg/context/ if err := b.httpSvr.Shutdown(ctx); err != nil { log.Error("OnDestroy Backend Shutdown error:%v", err) } log.Info("Backend: done. exiting") //一定别忘了继承 b.BaseModule.OnDestroy() log.Info("Backend 模块已销毁") }