gin 優雅重啟或停止
想要優雅地重啟或停止你的Web服務器,使用下面的方法
我們可以使用fvbock/endless來替換默認的ListenAndServe,有關詳細資訊,請參閱問題#296
router := gin.Default()
router.GET("/", handler)
// [...]
endless.ListenAndServe(":4242", router)
一個替換方案
- manners:一個Go HTTP服務器,能優雅的關閉
- graceful:Graceful是一個go的包,支持優雅地關閉http.Handler服務器
- grace:對Go服務器進行優雅的重啟和零停機部署
如果你的Go版本是1.8,你可能不需要使用這個庫,考慮使用http.Server內置的Shutdown()方法進行優雅關閉,查看例子
// +build go1.8
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"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: ":8080",
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)
signal.Notify(quit, os.Interrupt)
<-quit
log.Println("Shutdown Server ...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Server Shutdown:", err)
}
log.Println("Server exiting")
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/200731.html
標籤:其他
