服务启动项Hook
Hook顾名思义,为服务提供了一个插入自定义功能的入口,目前已有两个时间点的功能注册:服务启动之前 和服务停止之后,当然只要符合使用规范,也可以定义其他注册时机!
包路径
github.com/tal-tech/hera/bootstrap
定义
服务启动之前所执行函数的类型定义
type BeforeServerStartFunc func() error
服务停止之后所执行函数的类型定义
type AfterServerStopFunc func()
功能列表
//初始化日志库func InitLoggerWithConf(sections ...string) BeforeServerStartFunc//设置日志处理插件,适配网校trace日志格式func InitTraceLogger(department, version string) BeforeServerStartFunc//初始化打点库func InitPerfutil() BeforeServerStartFunc//设置fd为所允许的最大值func GrowMaxFd() BeforeServerStartFunc//初始化性能分析web服务func InitPprof() BeforeServerStartFunc
使用案例
假定我们写一个服务MyServer ,有两个属性切片属性beforeFuncs, afterFuncs 和两个添加hook函数的函数
type MyServer struct {beforeFuncs []bootstrap.BeforeServerStartFuncafterFuncs []bootstrap.AfterServerStopFunc}//AddBeforeServerStartFunc add before functionfunc (srv *MyServer) AddBeforeServerStartFunc(fns ...bootstrap.BeforeServerStartFunc) {for _, fn := range fns {srv.beforeFuncs = append(srv.beforeFuncs, fn)}}//AddAfterServerStopFunc add after functionfunc (srv *MyServer) AddAfterServerStopFunc(fns ...bootstrap.AfterServerStopFunc) {for _, fn := range fns {srv.afterFuncs = append(srv.afterFuncs, fn)}}//服务执行入口func (srv *MyServer) Serve() error {//服务执行前触发for _, fn := range srv.beforeFuncs {err := fn()if err != nil {return err}}//todo业务实现//服务退出后触发for _, fn := range srv.afterFuncs {fn()}}
