gin框架13--优雅地重启或停止
介绍
本文主要介绍 gin框架中重启或者停止的方案。常见的包括替换 ListenAndServe、manners、graceful、grace 等,go1.8可以考虑使用 http.Server 内置的 Shutdown() 方法优雅地关机。
案例
使用endless 来优雅重启
源码:
package main
import (
"github.com/fvbock/endless"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.String(200, "test shutdown!")
})
err := endless.ListenAndServe("localhost:8080", r)
print(err)
}
测试:
启动后,可以正常访问api, 输入 ^C 后收到 SIGINT信号,此时等待链接完成,在此期间还可以访问;
过一段时间后服务正常关闭,Serve() returning...,此时无法访问了
- using code: gin.SetMode(gin.ReleaseMode)
[GIN-debug] GET / --> main.main.func1 (3 handlers)
2022/03/24 08:14:38 40166 localhost:8080
[GIN] 2022/03/24 - 08:14:42 | 200 | 24.334µs | 127.0.0.1 | GET "/"
^C2022/03/24 08:14:46 40166 Received SIGINT.
2022/03/24 08:14:46 40166 Waiting for connections to finish...
2022/03/24 08:14:46 40166 127.0.0.1:8080 Listener closed.
[GIN] 2022/03/24 - 08:14:52 | 200 | 39.212µs | 127.0.0.1 | GET "/"
2022/03/24 08:14:52 40166 Serve() returning...
(0x809fe0,0xc0003b00a0)
Process finished with the exit code 0
使用 http.Server 内置的 Shutdown() 方法优雅地关机
源码
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() {
// 服务连接
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
// 等待中断信号以优雅地关闭服务器(设置 5 秒的超时时间)
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")
}
测试
启动后可以正常访问 api, ^C 后服务开始退出,并输出 Shutdown Server ..., 随后无法访问api
- using code: gin.SetMode(gin.ReleaseMode)
[GIN-debug] GET / --> main.main.func1 (3 handlers)
[GIN] 2022/03/24 - 08:22:08 | 200 | 5.003490467s | 127.0.0.1 | GET "/"
[GIN] 2022/03/24 - 08:22:18 | 200 | 5.00237298s | 127.0.0.1 | GET "/"
^C2022/03/24 08:22:38 Shutdown Server ...
2022/03/24 08:22:38 Server exiting
注意事项
上述方法可以用如下替代方案:
替代方案:
manners:可以优雅关机的 Go Http 服务器。
graceful:Graceful 是一个 Go 扩展包,可以优雅地关闭 http.Handler 服务器。
grace:Go 服务器平滑重启和零停机时间部署。
说明
https://gin-gonic.com/zh-cn/docs/examples/graceful-restart-or-stop/
github fvbock/endless