go1.8 http graceful shutdown example

go1.8 http graceful shutdown

go1.8 The HTTP server also adds support for graceful shutdown, allowing servers to minimize downtime by shutting down only after serving all requests that are in flight.

go 1.8 中提供了可以graceful shutdown的方式,关闭期间可以保证不再监听新的连接并服务于原有的连接不受影响(长连接除外),也可以设定 deadline timeout强制关闭,引入了 context来实现该机制。

Github代码(script)

[code lang=text]
package main

import (
"context"
"fmt"
"html"
"log"
"net/http"
"os"
"os/signal"
)

func main() {
// subscribe to SIGINT signals
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt)

srv := &http.Server{Addr: ":8080", Handler: http.DefaultServeMux}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})

go func() {
srv.ListenAndServe()
}

<-quit

log.Println("Shutting down server…")
if err := srv.Shutdown(context.Background()); err != nil {
log.Fatalf("could not shutdown: %v", err)
}
}
[/code]

如果要实现服务的平滑过渡,仍然需要保证Accept的延续性【当然也可以部署多实例保证一个实例关闭过程中,从LB中移除,其他的实例能够保证服务】,保证server关闭期间能够平滑过渡,可以参考另一篇文章: 程序的无缝重启

源代码地址:https://gist.github.com/DavadDi/4048e796873205296802e21e34dc0325

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注