新聞中心
大家好,我是 polarisxu。

和靜網(wǎng)站制作公司哪家好,找成都創(chuàng)新互聯(lián)!從網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、成都響應(yīng)式網(wǎng)站建設(shè)公司等網(wǎng)站項(xiàng)目制作,到程序開發(fā),運(yùn)營維護(hù)。成都創(chuàng)新互聯(lián)自2013年創(chuàng)立以來到現(xiàn)在10年的時(shí)間,我們擁有了豐富的建站經(jīng)驗(yàn)和運(yùn)維經(jīng)驗(yàn),來保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選成都創(chuàng)新互聯(lián)。
os/signal 這個包大家可能用的不多。但自從 Go1.8 起,有些人開始使用這個包了,原因是 Go1.8 在 net/http 包新增了一個方法:
- func (srv *Server) Shutdown(ctx context.Context) error
有了它就不需要借助第三方庫實(shí)現(xiàn)優(yōu)雅關(guān)閉服務(wù)了。具體怎么做呢?
- func main() {
- server = http.Server{
- Addr: ":8080",
- }
- http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
- time.Sleep(time.Second * 10)
- fmt.Fprint(w, "Hello world!")
- })
- go server.ListenAndServe()
- // 監(jiān)聽中斷信號(CTRL + C)
- c := make(chan os.Signal, 1)
- signal.Notify(c, os.Interrupt)
- <-c
- // 重置 os.Interrupt 的默認(rèn)行為
- signal.Reset(os.Interrupt)
- fmt.Println("shutting down gracefully, press Ctrl+C again to force")
- // 給程序最多 5 秒時(shí)間處理正在服務(wù)的請求
- timeoutCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- if err := server.Shutdown(timeoutCtx); err != nil {
- fmt.Println(err)
- }
- }
- 這里利用 os/signal 包監(jiān)聽 Interrupt 信號;
- 收到該信號后,16 行 <-c 會返回;
- 為了可以再次 CTRL + C 強(qiáng)制退出,通過 Reset 恢復(fù) os.Interrupt 的默認(rèn)行為;(這不是必須的)
優(yōu)雅退出的關(guān)鍵:1)新請求進(jìn)不來;2)已有請求給時(shí)間處理完。所以,在接收到信號后,調(diào)用 server.Shutdown 方法,阻止新請求進(jìn)來,同時(shí)給 5 秒等待時(shí)間,讓已經(jīng)進(jìn)來的請求有時(shí)間處理。
在 Go1.16 中,os/signal 包新增了一個函數(shù):
- func NotifyContext(parent context.Context, signals ...os.Signal) (ctx context.Context, stop context.CancelFunc)
功能和 Notify 類似,但用法上有些不同。上面的例子改用 NotifyContext:
- func after() {
- server = http.Server{
- Addr: ":8080",
- }
- http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
- time.Sleep(time.Second * 10)
- fmt.Fprint(w, "Hello world!")
- })
- go server.ListenAndServe()
- // 監(jiān)聽中斷信號(CTRL + C)
- ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
- <-ctx.Done()
- // 重置 os.Interrupt 的默認(rèn)行為,類似 signal.Reset
- stop()
- fmt.Println("shutting down gracefully, press Ctrl+C again to force")
- // 給程序最多 5 秒時(shí)間處理正在服務(wù)的請求
- timeoutCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- if err := server.Shutdown(timeoutCtx); err != nil {
- fmt.Println(err)
- }
- }
和上面的寫法有區(qū)別,完成的功能一樣的。其實(shí) NotifyContext 的內(nèi)部就是基于 Notify 實(shí)現(xiàn)的:
- func NotifyContext(parent context.Context, signals ...os.Signal) (ctx context.Context, stop context.CancelFunc) {
- ctx, cancel := context.WithCancel(parent)
- c := &signalCtx{
- Context: ctx,
- cancel: cancel,
- signals: signals,
- }
- c.ch = make(chan os.Signal, 1)
- Notify(c.ch, c.signals...)
- if ctx.Err() == nil {
- go func() {
- select {
- case <-c.ch:
- c.cancel()
- case <-c.Done():
- }
- }()
- }
- return c, c.stop
- }
只是在返回的 stop 被調(diào)用時(shí),會執(zhí)行 os/signal 包中的 Stop 函數(shù),這個 Stop 函數(shù)的功能和 Reset 類似。因此上面 Notify 的例子,Reset 的地方可以改為 Stop。
從封裝上看,NotifyContext 做的更好。而且,如果在某些需要 Context 的場景下,它把監(jiān)控系統(tǒng)信號和創(chuàng)建 Context 一步搞定。
NotifyContext 的用法,優(yōu)雅的關(guān)閉服務(wù),你掌握了嗎?希望你實(shí)際動手試驗(yàn)下,啟動服務(wù),通過 curl http://localhost:8080/ 訪問,然后按 CTRL + C,看看具體效果。只看不動手,基本知識不是你的。
關(guān)于 NotifyContext 函數(shù)的文檔可以在這里查看:https://docs.studygolang.com/pkg/os/signal/#NotifyContext。
本文轉(zhuǎn)載自微信公眾號「polarisxu」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系polarisxu公眾號。
分享文章:Go1.16中的新函數(shù)Signal.NotifyContext怎么用?
鏈接分享:http://m.fisionsoft.com.cn/article/ccopsdg.html


咨詢
建站咨詢
