Gin
的启动流程
今天我们介绍Gin
平滑停机。首先我们看一下,Gin
在的启动流程,如下图。所有的处理逻辑在Run()
函数中,里面还是调用底层的TCP
连接的listen
函数。
Gin
平滑停机流程
有时候我们服务器停机之前处理完之前接收的请求,这就是所谓优雅停机或者平滑停机。其流程见下图:
Gin
平滑停机示例代码
package main
import (
"context"
"github.com/gin-gonic/gin"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
router := gin.Default()
router.GET("/testing", func(c *gin.Context) {
time.Sleep(10 * time.Second)
c.JSON(http.StatusOK, gin.H{
"message":"Welcom Gin Srever",
})
})
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 10 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(), 10 * time.Second)
defer cancel()
if err:= srv.Shutdown(ctx); err != nil {
log.Fatal("Server Shutdown:", err)
}
log.Println("Server exiting")
}
测试
- 启动服务
[GIN-debug] GET /testing --> main.main.func1 (3 handlers)
- 命令窗口:
curl "localhost:8080/testing"
- 停止服务
2020/03/17 08:35:09 Shutdown Server ...
[GIN] 2020/03/17 - 08:35:17 | 200 | 10.002280953s | 127.0.0.1 | GET /testing
2020/03/17 08:35:18 Server exiting
- 观察命令窗口
{"message":"Welcom Gin Srever"}