使用Gin如何优雅的停止监听
洪笳淏 Lv4

暴力停止

  我们在 go run main.go 后,若需要停止监听,需要使用 ctrl+c 终止监听。该方案会立即终止服务器监听,同时结束正在处理的请求,也就是说若存在未处理完毕的请求,是不能继续处理的。

1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import "github.com/gin-gonic/gin"

func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run() // 监听并在 0.0.0.0:8080 上启动服务
}

优雅停止

  代替示例代码中 router.Run() 方法,我们可以使用 http.Server 内置的 Shutdown() 方法优雅地停止。所谓优雅,指的是可以将正在处理的请求处理完毕后再关闭服务器。示例代码如下 main.go :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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,
}
// 利用 goroutine 启动监听
go func() {
// srv.ListenAndServe() 监听
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 信道是同步信道,若没有信号进来,处于阻塞状态
// 反之,则执行后续代码
<-quit
log.Println("Shutdown Server ...")

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// 调用 srv.Shutdown() 完成优雅停止
// 调用时传递了一个上下文对象,对象中定义了超时时间
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Server Shutdown:", err)
}
log.Println("Server exiting")
}

测试以上代码,结果为:

1
2
3
4
5
6
7
8
9
10
11
$ go run main.go
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env: export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET / --> main.main.func1 (3 handlers)
2019/11/05 22:49:04 Shutdown Server ...
[GIN] 2019/11/05 - 22:49:07 | 200 | 5.0000438s | ::1 | GET /
2019/11/05 22:49:08 Server exiting
  • Post title:使用Gin如何优雅的停止监听
  • Post author:洪笳淏
  • Create time:2021-12-08 19:34:00
  • Post link:https://jiahaohong1997.github.io/2021/12/08/使用Gin如何优雅的停止监听/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.
 Comments