This is a creation in Article, where the information may have evolved or changed.
Many times the practice of service escalation is simple and brutal, and a simple kill process starts a new process.
There is a good point is that multiple identical services are upgraded in order to ensure that services are available. But it's fair to say both of these will lose the connection in the request.
In view of this, in reality we can use graceful restart to solve this problem. Golang's principle of graceful restart is simple:
Monitor USR2 signal;
When the signal is received, the file descriptor of the service listener is passed to the new child process;
At this time the new and old process to receive requests;
The parent process stops receiving new requests and waits for the old request to complete (or time out);
The parent process exits.
For the above principle seems simple, in fact, is divided into two major points:
The new and old process simultaneously listens to the same port, this is very simple, Go very early old support;
How to wait for the old request to complete, it takes a while before Go 1.8 (new Server.shutdown).
Now that we've taken care of the above principle, plus Go 1.8 's perfect waiting for the old request to be fulfilled,
I implemented a simple graceful restart library: Https://github.com/douglarek/zerodown.
zerodown
Perfect compatibility based on Go Standard library Server monitoring service.
For the use of standard libraries, we can use them as follows:
package mainimport ( "fmt" "log" "net/http" "time" "github.com/douglarek/zerodown")func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { time.Sleep(5 * time.Second) fmt.Fprintln(w, "Hello, World!") }) log.Fatalln(zerodown.ListenAndServe(":8080", nil))
For third-party libraries Gin we can:
package mainimport ( "log" "net/http" "time" "github.com/douglarek/zerodown" "github.com/gin-gonic/gin")func main() { router := gin.Default() router.GET("/", func(c *gin.Context) { time.Sleep(5 * time.Second) c.String(http.StatusOK, "Hello, World!") }) log.Fatalln(zerodown.ListenAndServe(":8080", router))}