0%

gin 项目优雅地关闭

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
49
50
51
52
53
54
55
56
57
58
59
package main

import (
"context"
"fmt"
"github.com/gin-contrib/pprof"
"github.com/gin-gonic/gin"
"net/http"
"os"
"os/signal"
"syscall"
_ "t/router"
"time"
)

func main() {
r := gin.Default()

r.Use(gin.Recovery())
r.Use(gin.Logger())
pprof.Register(r)
r.GET("/ping", func(c *gin.Context) {

c.JSON(200, gin.H{
"message": "pong",
})
})

server := &http.Server{
Addr: ":10000",
Handler: r,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}

go server.ListenAndServe()

// 设置优雅退出
gracefulExit(server)
}

func gracefulExit(server *http.Server) {
ch := make(chan os.Signal)
signal.Notify(ch, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGINT, syscall.SIGKILL)
sig := <-ch

fmt.Println("got a signal", sig)
now := time.Now()
cxt, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := server.Shutdown(cxt)
if err != nil {
fmt.Println("err", err)
}

// 看看实际退出所耗费的时间
fmt.Println("------exited--------", time.Since(now))
}