优雅重启或停止
您想优雅地重新启动或停止您的网络服务器吗?有一些方法可以做到这一点。
我们可以使用 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() 方法来优雅地关闭。请参阅完整的 graceful-shutdown 与 gin 的示例。
// +build go1.8
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: ":8080",
Handler: router.Handler(),
}
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, 1)
// kill (no param) default send syscall.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 ...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Server Shutdown:", err)
}
// catching ctx.Done(). timeout of 5 seconds.
select {
case <-ctx.Done():
log.Println("timeout of 5 seconds.")
}
log.Println("Server exiting")
}