你如何优雅地退出一个超级fx应用程序

你如何停止一个uber fx,就像关闭整个程序一样。似乎除了ctrl+c之外没有其他方法。


func main() {

    fx.New(

        fx.Invoke(register)

    ).Run

}



func register() {

    time.Sleep(5*time.Seconds)

    // shutdown somehow

}



白衣非少年
浏览 166回答 2
2回答

RISEBY

文档不是特别清楚,但是有一个接口可用于任何Fx模块,该接口具有请求正常关闭应用程序的方法。ShutdownerShutdown下面是示例包的修改部分,它将在收到请求时将其简单地关闭:func NewHandler(logger *log.Logger, shutdowner fx.Shutdowner) (http.Handler, error) {    logger.Print("Executing NewHandler.")    return http.HandlerFunc(func(http.ResponseWriter, *http.Request) {        logger.Print("Got a request. Requesting shutdown now that I've gotten one request.")        shutdowner.Shutdown()    }), nil}编辑:以下是修改解决方案的方法:func register(shutdowner fx.Shutdowner) {    time.Sleep(5*time.Seconds)    shutdowner.Shutdown()}

尚方宝剑之说

您可以将其包装在 go 例程中,并使用上下文优雅地退出。&nbsp;import (&nbsp; &nbsp; "context"&nbsp; &nbsp; "log"&nbsp; &nbsp; " go.uber.org/fx")func main() {&nbsp; &nbsp; f := fx.New(fx.Invoke(register))&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; f.Run()&nbsp; &nbsp; }()&nbsp; &nbsp; stopCh := make(chan os.Signal)&nbsp; &nbsp; signal.Notify(stopCh, syscall.SIGINT, syscall.SIGTERM)&nbsp; &nbsp; <-stopCh&nbsp; &nbsp; if err := f.Stop(context.Background()); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Printf("error stopping gracefully")&nbsp; &nbsp; }}func register() {&nbsp; &nbsp; time.Sleep(5*time.Seconds)&nbsp; &nbsp; // shutdown somehow}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go