Golang笔记

Go 应用优雅重启的方法

Go 应用优雅重启的方法

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
}

测试:

curl 'http://localhost:48567/?duration=20s'
kill -USR2 <server pid>
curl 'http://localhost:48567/?duration=0s'

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

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