Gin 使用示例(十八):平滑重启或关闭服务器


可以使用 fvbock/endless 来替换默认的 ListenAndServe 方法,参考 https://github.com/gin-gonic/gin/issues/296 这个 issue 了解更多细节:

router := gin.Default()
router.GET("/", handler)
// [...]
endless.ListenAndServe(":4242", router)

其他可替代方案:

如果你使用的是 Go 1.8 及以上版本,不需要依赖第三方扩展包,使用 http.Server 内置的 Shutdown() 方法即可平滑关闭服务器:

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,
  }

  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 ...")

  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")
}

Ctrl+C 退出时,等待所有请求处理完成后退出:

-w866


点赞 取消点赞 收藏 取消收藏

<< 上一篇: Gin 使用示例(十七):实现 HTTP/2 服务器推送

>> 下一篇: Gin 使用示例(十九):JSONP