为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
白衣非少年 2022-08-01 18:04:11
你如何停止一个uber fx,就像关闭整个程序一样。似乎除了ctrl+c之外没有其他方法。func main() {    fx.New(        fx.Invoke(register)    ).Run}func register() {    time.Sleep(5*time.Seconds)    // shutdown somehow}
查看完整描述

2 回答

?
RISEBY

TA贡献1856条经验 获得超5个赞

文档不是特别清楚,但是有一个接口可用于任何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()

}


查看完整回答
反对 回复 2022-08-01
?
尚方宝剑之说

TA贡献1788条经验 获得超4个赞

您可以将其包装在 go 例程中,并使用上下文优雅地退出。


 import (

    "context"

    "log"

    " go.uber.org/fx"

)



func main() {

    f := fx.New(fx.Invoke(register))


    go func() {

        f.Run()

    }()


    stopCh := make(chan os.Signal)

    signal.Notify(stopCh, syscall.SIGINT, syscall.SIGTERM)

    <-stopCh


    if err := f.Stop(context.Background()); err != nil {

        log.Printf("error stopping gracefully")

    }

}



func register() {

    time.Sleep(5*time.Seconds)

    // shutdown somehow

}


查看完整回答
反对 回复 2022-08-01
  • 2 回答
  • 0 关注
  • 165 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号