GolangNote

Golang笔记

Go 应用优雅重启的方法

Permalink

Go 应用优雅重启的方法

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

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

        "github.com/facebookgo/grace/gracehttp"
)

var (
        address0 = flag.String("a0", ":48567", "Zero address to bind to.")
        address1 = flag.String("a1", ":48568", "First address to bind to.")
        address2 = flag.String("a2", ":48569", "Second address to bind to.")
        now      = time.Now()
)

func main() {
        flag.Parse()
        gracehttp.Serve(
                &http.Server{Addr: *address0, Handler: newHandler("Zero  ")},
//              &http.Server{Addr: *address1, Handler: newHandler("First ")},
//              &http.Server{Addr: *address2, Handler: newHandler("Second")},
        )
}

func newHandler(name string) http.Handler {
        mux := http.NewServeMux()
        mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
                fmt.Fprintf(w, "halou hahhha 6")
        })
"grace.go" 52L, 1196C
                duration, err := time.ParseDuration(r.FormValue("duration"))
                if err != nil {
                        http.Error(w, err.Error(), 400)
                        return
                }
                time.Sleep(duration)
                fmt.Fprintf(
                        w,
                        "%s started at %s slept for %d nanoseconds from pid %d.\n",
                        "name",
                        now,
                        duration.Nanoseconds(),
                        os.Getpid(),
                )
        })
        return mux
}

测试:

Bash: 优雅重启测试
1
2
3
curl 'http://localhost:48567/?duration=20s'
kill -USR2 <server pid>
curl 'http://localhost:48567/?duration=0s'

来源 https://github.com/facebookgo/grace

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

Related articles

Go 编程格言谚语

这些 go 格言谚语大多出自 Rob Pike 振奋人心的演讲视频,有很大参考价值。...

Go 1.5.1 更新的功能

Go 1.5.1版本对编译器,汇编器, fmt, net/textproto, net/http, 和 runtime 包的 bug 修复。...

Write a Comment to "Go 应用优雅重启的方法"

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