go 程序优雅退出的步骤很简单
- 注册信号
- 接收信号
- 处理信号
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
)
func main() {
// Go signal notification works by sending `os.Signal`
// values on a channel. We'll create a channel to
// receive these notifications (we'll also make one to
// notify us when the program can exit).
sigs := make(chan os.Signal, 1)
done := make(chan bool, 1)
// `signal.Notify` registers the given channel to
// receive notifications of the specified signals.
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
// This goroutine executes a blocking receive for
// signals. When it gets one it'll print it out
// and then notify the program that it can finish.
go func() {
sig := <-sigs
fmt.Println()
fmt.Println(sig)
done <- true
}()
// The program will wait here until it gets the
// expected signal (as indicated by the goroutine
// above sending a value on `done`) and then exit.
fmt.Println("awaiting signal")
<-done
fmt.Println("exiting")
}
gin 优雅退出
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.GET("/", func(c *gin.Context) {
time.Sleep(5 * time.Second)
c.String(http.StatusOK, "Welcome Gin Server")
})
srv := &http.Server{
Addr: ":8081",
Handler: router,
}
// 使用协程启动服务,主进程完成信号注册、接收、退出操作
go func() {
// service connections
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
// Wait for interrupt signal to gracefully shutdown the server with
// a timeout of 5 seconds.
// 声明一个接收信号的管道
quit := make(chan os.Signal)
// kill (no param) default send syscanll.SIGTERM
// kill -2 is syscall.SIGINT
// kill -9 is syscall. SIGKILL but can"t be catch, so don't need add it
// 注册接收的退出的信号,可以注册多个信号,接收到的信号会向管道内写入数据
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
// 只有接收到退出的信号才会读取到数据执行退出的操作,要不然就阻塞在这个地方
<-quit
log.Println("Shutdown Server ...")
// 生成可退出协程的context
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// 退出web server,退出的时候会向ctx写入数据
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Server Shutdown:", err)
}
// catching ctx.Done(). timeout of 5 seconds.
// 阻塞读取ctx向管道内写入的数据并退出
select {
case <-ctx.Done():
log.Println("timeout of 5 seconds.")
}
log.Println("Server exiting")
// 这时候服务也就退出了,主进程也结束了,协程也跟着结束了
}