ijd8.COM

A simple blog for an old Ma Nong.

使用Golang原生库实现 Web 服务优雅重启

Permalink

当应用重新编译后需要重新部署,就会面临一些问题,主要是等待处理中的请求、打开资源的置放,这就需要一个比较好的方法来实现优雅重启。

比较了多种方法,最后选择使用原生库来实现,比较靠谱,也比较方便。

系统中断信号

  • kill 默认会发送 syscall.SIGTERM 信号
  • kill -2 发送 syscall.SIGINT 信号,常用的Ctrl+C就是触发系统SIGINT信号
  • kill -9 发送 syscall.SIGKILL 信号,但是不能被捕获,所以不需要添加它

完整代码

Go: graceful restart
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main

import (
	"context"
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())

	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		log.Println("bg->")
		time.Sleep(15 * time.Second)
		_, _ = fmt.Fprintf(w, "okay")
		log.Println("<-ed")
	})

	httpServer := &http.Server{
		Addr:        ":8082",
		Handler:     mux,
		BaseContext: func(_ net.Listener) context.Context { return ctx },
	}
	// 注册 Shutdown cancel,如果没有下面这一行,则需要在下文适当位置调用函数 cancel()
	httpServer.RegisterOnShutdown(cancel)

	// 运行 http server
	go func() {
		if err := httpServer.ListenAndServe(); err != http.ErrServerClosed {
			// 因为不是主 goroutine,推荐使用 Fatalf 来终止应用
			log.Fatalf("HTTP server ListenAndServe: %v", err)
		}
	}()

	// 上面是正常 web server 启动
	// 下面是 graceful 实现
	signalChan := make(chan os.Signal, 1)

	signal.Notify(
		signalChan,
		syscall.SIGHUP,  // kill -SIGHUP XXXX
		syscall.SIGINT,  // kill -SIGINT XXXX or Ctrl+c
		syscall.SIGTERM, // kill -SIGTERM XXXX
		syscall.SIGQUIT, // kill -SIGQUIT XXXX
	)

	<-signalChan
	log.Print("os.Interrupt - shutting down...\n")

	go func() {
		<-signalChan
		log.Fatal("os.Kill - terminating...\n")
	}()

	// 设置 30 秒超时,等待请求完成(如果没有请求则会立即关闭),同时也阻止新的请求进来
	gracefulCtx, cancelShutdown := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancelShutdown()

	if err := httpServer.Shutdown(gracefulCtx); err != nil {
		log.Printf("shutdown error: %v\n", err)
		defer os.Exit(1)
		return
	} else {
		log.Printf("gracefully stopped\n")
	}

	// manually cancel context if not using httpServer.RegisterOnShutdown(cancel)
	cancel()

	defer os.Exit(0)
	return
}

我一般使用 Supervisor 来守护进程,在配置时参数 stopwaitsecs 的值要比 context.WithTimeout 设置的超时时间大一点,否则会被强行杀掉的。比如上文设置 30秒:

INI: supervisord.conf
1
2
3
4
5
6
7
8
[program:ijd8]
command = /bin/ijd8
process_name = ijd8
stopwaitsecs = 31
directory = /root/ijd8
redirect_stderr=true
autostart=true
autorestart=true

参考

https://github.com/vardius/shutdown

Write a Comment

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.16.7 Processed in 1ms