优雅地退出 go 应用程序

我是 Go 新手,我正在运行一些小服务。

当我部署一个新版本时,我通常只是上传新的二进制文件、kill现有的进程并开始一个新的进程。

我想知道这是否是正确的做法,或者是否有更好的方法来做到这一点。


莫回无
浏览 125回答 1
1回答

一只名叫tom的猫

杀死进程,替换和重新启动没有任何问题。如果您想在退出时进行一些清理,您可以执行以下操作:import(&nbsp; &nbsp;"fmt"&nbsp; &nbsp;"os"&nbsp; &nbsp;"os/signal"&nbsp; &nbsp;"syscall")func main(){&nbsp; &nbsp;//work here&nbsp; &nbsp;go gracefulShutdown()&nbsp; &nbsp;forever := make(chan int)&nbsp; &nbsp;<-forever}func gracefulShutdown() {&nbsp; &nbsp; s := make(chan os.Signal, 1)&nbsp; &nbsp; signal.Notify(s, os.Interrupt)&nbsp; &nbsp; signal.Notify(s, syscall.SIGTERM)&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; <-s&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Sutting down gracefully.")&nbsp; &nbsp; &nbsp; &nbsp; // clean up here&nbsp; &nbsp; &nbsp; &nbsp; os.Exit(0)&nbsp; &nbsp; }()}如果您确实 kill {pid} (没有 -9 开关),进程将gracefullShutdown在终止之前调用函数。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go