GolangNote

Golang笔记

supervisord golang 1.8+ 优雅重启

Permalink

supervisord 守护golang 进程,实现优雅重启的例子

supervisord golang 1.8+ 优雅重启

Go: fraceful
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"
	"io"
	"log"
	"net"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

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

	// subscribe to SIGINT signals
	stopChan := make(chan os.Signal, 1)
	signal.Notify(stopChan, os.Interrupt, syscall.SIGTERM, syscall.SIGINT, syscall.SIGUSR2)

	mux := http.NewServeMux()

	mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		time.Sleep(10 * time.Second)
		_,_=io.WriteString(w, "Finished!")
	}))

	srv := &http.Server{
		Addr: ":8081",
		Handler: mux,
		BaseContext: func(_ net.Listener) context.Context { return ctx },
	}
	srv.RegisterOnShutdown(cancel)

	go func() {
		// service connections
		if err := srv.ListenAndServe(); err != nil {
			log.Printf("listen: %s\n", err)
		}
	}()

	<-stopChan // wait for SIGINT
	log.Println("Shutting down server...")

	// shut down gracefully, but wait no longer than 10 seconds before halting
	gracefulCtx, cancelShutdown := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancelShutdown()
	if err := srv.Shutdown(gracefulCtx); err != nil {
		log.Printf("shutdown error: %v\n", err)
		defer os.Exit(1)
		return
	} else {
		//app.Close() // !important 留意上下文位置
		log.Printf("gracefully stopped\n")
	}
	log.Println("Server gracefully stopped")

}

supervisord.conf 配置

INI: supervisord.conf
1
2
3
4
5
6
7
8
9
10
[program:test]
;user=root
command = /srv/www/test/test
process_name = test
directory = /srv/www/test
redirect_stderr=true
autostart=true
autorestart=true
stopwaitsecs = 11
stopsignal = INT

关键两行:

INI: stopwaitsecs
1
2
stopwaitsecs = 11
stopsignal = INT

Related articles

Golang http IPv4/IPv6 服务

Golang 的网络服务,如果不指定IPv4 或 IPv6,如果VPS 同时支持 IPv4 和 IPv6,`net.Listen()` 只会监听 IPv6 地址。但这不影响客户端使用 IPv4 地址来访问。...

Golang 生成防识别的图片验证码

验证码 captcha 是对抗密码强力破解、垃圾信息的有效方式,一般用于用户注册、登录,当检测到频繁发帖时也会启用验证码。下面介绍用golang 生成防机器识别的图片验证码。...

Golang 把cookie 字符串解析为cookie 结构

在做爬虫时有时候会遇到需要带已登录的 cookie 请求,这个时候最简单的方法是在浏览器登录后,在开发者面板找到cookie 字符串,然后拷贝粘贴。这就面临一个问题需要把cookie 字符串解析成Go 语言 cookie 结构体。...

golang rot13 简单加密字符

ROT13 是一种简单的字符加密方法,把 26 个英文字母的前 13 个字母与后 13 个字母的编码互换。...

Write a Comment to "supervisord golang 1.8+ 优雅重启"

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