GolangNote

Golang笔记

golang 应用热重启的例子 graceful

Permalink

我使用的是 gopkg.in/tylerb/graceful 包,

Go: graceful
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
package main

import (
    "fmt"
    "net/http"
    "os"
    "time"

    "gopkg.in/tylerb/graceful.v1"
)

var (
    now = time.Now()
)

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        duration, err := time.ParseDuration(r.FormValue("duration"))
        if err != nil {
            http.Error(w, err.Error(), 400)
            return
        }
        time.Sleep(duration)
        fmt.Fprintf(
            w,
            "started at %s slept for %d nanoseconds from pid %d.\n",
            now,
            duration.Nanoseconds(),
            os.Getpid(),
        )
    })

    graceful.Run(":3001", 21*time.Second, mux)
}

supervisord.conf 配置示例

INI: supervisord conf
1
2
3
4
5
6
7
8
9
[program:golangn]
;user=root
command = /Users/weis/tmp/graceful2
process_name = golangnote
stopwaitsecs = 22
directory = /Users/weis/tmp
redirect_stderr=true
autostart=true
autorestart=true

需要注意的地方是两个 timeout 时间:

Go: graceful
1
2
graceful.Run(":3001", 21*time.Second, mux)
stopwaitsecs = 22

supervisord.conf 里的时间要比 go 脚本里的时间多 1 秒。

测试

Bash: 热重启测试
1
2
3
4
5
curl 'http://localhost:3001/?duration=20s'
curl 'http://localhost:3001/?duration=20s'
curl 'http://localhost:3001/?duration=0s'
supervisorctl restart all
curl 'http://localhost:3001/?duration=0s'

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

Related articles

goji + SSDB 构建的应用

已经过了学生的年纪,学习新东西不那么快,尝试从python 转向golang,就从博客程序开始。...

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

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

Write a Comment to "golang 应用热重启的例子 graceful"

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