今天做了一个go语音的http server优雅退出的测试实验
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
t:=time.NewTimer(6 * time.Second)
L: for {
time.Sleep(1*time.Second)
select {
case <- t.C:
fmt.Println("\ntime out===============================")
break L
default:
fmt.Println("i am doing job")
}
}
fmt.Fprintf(w, "Hello World, %v\n", time.Now())
})
s := &http.Server{
Addr: ":8080",
Handler: http.DefaultServeMux,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
go func() {
log.Println(s.ListenAndServe())
log.Println("server shutdown")
}()
// Handle SIGINT and SIGTERM.
ch := make(chan os.Signal)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
log.Println(<-ch)
// Stop the service gracefully.
log.Println(s.Shutdown(context.Background()))
// Wait gorotine print shutdown message
log.Println("done.")
}
在正常访问服务的时候,会一直打印出 i am doing job, 并在6s之后返回数据
curl http://localhost:8080/
试一下,6s没到,就把服务给停掉,看服务能否优雅退出
服务还是能优雅退出
证明go1.8版本的 server.shutdown(context) 就考虑了优雅退出,只需要调用就好了
进一步需要思考的问题:在使用这个shutdown函数的时候这个context传什么?nil 还是Background()还是其他?