Golang笔记

golang 应用热重启的例子 graceful

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

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 配置示例

[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 时间:

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

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

测试:

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 (转载注明出处)
关于GolangNote:记录在工作中使用golang 遇到、面临的相关问题及解决方法。如果你在这里获得一些知识或信息,解决你的编程问题,请考虑捐赠给不幸的人或者你喜欢的慈善机构,除捐赠外,种植树木、志愿服务或减少排碳的行为也很有益处。如果你有任何问题可以在下面 留言
Be the first to comment!
Captcha image
Relative Articles