GolangNote

Golang笔记

supervisord golang 1.8+ 优雅重启

Permalink

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

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
60
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

本文网址: https://golangnote.com/topic/179.html 转摘请注明来源

Related articles

golang 实现的基于web的文件管理-filebrowser

FileBrowser 在指定目录中提供了一个文件管理界面,可用于上传,删除,预览,重命名和编辑文件。它允许创建多个用户,每个用户都可以有自己的目录。它可以用作独立的应用程序。...

谷歌翻译的 golang 库推荐

Google 的翻译越来越好了,官方的Golang SDK 已经很完美,这里介绍的是几个非官方发布的有特色的库。...

Golang sync.WaitGroup 的 Wait 超时处理

sync.WaitGroup 使用 `Add(1)`、`Done()`、`Wait()`组合来实现多协程等待,如果某一协程未能合理处理错误,导致无法退出,此时需要引入超时机制。下面是一种超时处理方法。...

golang共享数据用Mutex 或 Channel

在go 里,多线程对共享数据的操作一般要使用Mutex 或 Channel 来加锁或隔离通信。下面是一个使用Mutex 和 Channel 比较的例子。...

Golang Web 程序生产环境独立部署示例

一个 web 应用通常是跑在一个前端代理,如 Nginx 后,这样可以方便的在同一个服务器部署多个应用。这里说的独立部署是指让 go web 程序直接暴露在外面,独占 443、80 端口(俗称裸跑)。这样做除了性能有些提高外,更重要的是部署方便。...

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

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 0ms