Golang 如何優雅的終止一個服務?

大家好,我是浩然,網名 “磊磊落落”。專注 Golang、算法、DevOps、PostgreSQL 及雲原生,想學新技術,關注我就對了!

https://leileiluoluo.com

採用常規方式啓動一個 Golang http 服務時,若服務被意外終止或中斷,即未等待服務對現有請求連接處理並正常返回且亦未對服務停止前作一些必要的處理工作,這樣即會造成服務硬終止。這種方式不是很優雅。

參看如下代碼,該 http 服務請求路徑爲根路徑,請求該路徑,其會在 2s 後返回 hello。

var addr = flag.String("server addr"":8080""server address")

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        time.Sleep(2 * time.Second)
        fmt.Fprintln(w, "hello")
    })
    http.ListenAndServe(*addr, nil)
}

若服務啓動後,請求http://localhost:8080/,然後使用 Ctrl+C 立即中斷服務,服務即會立即退出(exit status 2),請求未正常返回(ERR_CONNECTION_REFUSED),連接即馬上斷了。

接下來介紹使用 http.Server 的 Shutdown 方法結合 signal.Notify 來優雅的終止服務。

1 Shutdown 方法

Golang http.Server 結構體有一個終止服務的方法 Shutdown,其 go doc 如下。

func (srv *Server) Shutdown(ctx context.Context) error
    Shutdown gracefully shuts down the server without interrupting any active
    connections. Shutdown works by first closing all open listeners, then
    closing all idle connections, and then waiting indefinitely for connections
    to return to idle and then shut down. If the provided context expires before
    the shutdown is complete, Shutdown returns the context's error, otherwise it
    returns any error returned from closing the Server's underlying Listener(s).

    When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS
    immediately return ErrServerClosed. Make sure the program doesn't exit and
    waits instead for Shutdown to return.

    Shutdown does not attempt to close nor wait for hijacked connections such as
    WebSockets. The caller of Shutdown should separately notify such long-lived
    connections of shutdown and wait for them to close, if desired. See
    RegisterOnShutdown for a way to register shutdown notification functions.

    Once Shutdown has been called on a server, it may not be reused; future
    calls to methods such as Serve will return ErrServerClosed.

由文檔可知:

使用 Shutdown 可以優雅的終止服務,其不會中斷活躍連接。

其工作過程爲:首先關閉所有開啓的監聽器,然後關閉所有閒置連接,最後等待活躍的連接均閒置了才終止服務。

若傳入的 context 在服務完成終止前已超時,則 Shutdown 方法返回 context 的錯誤,否則返回任何由關閉服務監聽器所引起的錯誤。

當 Shutdown 方法被調用時,Serve、ListenAndServe 及 ListenAndServeTLS 方法會立刻返回 ErrServerClosed 錯誤。請確保 Shutdown 未返回時,勿退出程序。

對諸如 WebSocket 等的長連接,Shutdown 不會嘗試關閉也不會等待這些連接。若需要,需調用者分開額外處理(諸如通知諸長連接或等待它們關閉,使用 RegisterOnShutdown 註冊終止通知函數)。

一旦對 server 調用了 Shutdown,其即不可再使用了(會報 ErrServerClosed 錯誤)。

有了 Shutdown 方法,我們知道在服務終止前,調用該方法即可等待活躍連接正常返回,然後優雅的關閉。

但服務啓動後的某一時刻,程序如何知道服務被中斷了呢?服務被中斷時如何通知程序,然後調用 Shutdown 作處理呢?接下來看一下系統信號通知函數的作用。

2 signal.Notify 函數

signal 包的 Notify 函數提供系統信號通知的能力,其 go doc 如下。

func Notify(c chan<- os.Signal, sig ...os.Signal)
    Notify causes package signal to relay incoming signals to c. If no signals
    are provided, all incoming signals will be relayed to c. Otherwise, just the
    provided signals will.

    Package signal will not block sending to c: the caller must ensure that c
    has sufficient buffer space to keep up with the expected signal rate. For a
    channel used for notification of just one signal value, a buffer of size 1
    is sufficient.

    It is allowed to call Notify multiple times with the same channel: each call
    expands the set of signals sent to that channel. The only way to remove
    signals from the set is to call Stop.

    It is allowed to call Notify multiple times with different channels and the
    same signals: each channel receives copies of incoming signals
    independently.

由文檔可知:

參數 c 是調用者的信號接收通道,Notify 可將進入的信號轉到 c。sig 參數爲需要轉發的信號類型,若不指定,所有進入的信號都將會轉到 c。

信號不會阻塞式的發給 c:調用者需確保 c 有足夠的緩衝空間,以應對指定信號的高頻發送。對於用於通知僅一個信號值的通道,緩衝大小爲 1 即可。

同一個通道可以調用 Notify 多次:每個調用擴展了發送至該通道的信號集合。僅可調用 Stop 來從信號集合移除信號。

允許不同的通道使用同樣的信號參數調用 Notify 多次:每個通道獨立的接收進入信號的副本。

綜上,有了 signal.Notify,傳入一個 chan 並指定中斷參數,這樣當系統中斷時,即可接收到信號。

參看如下代碼,當使用 Ctrl+C 時,c 會接收到中斷信號,程序會在打印 “program interrupted” 語句後退出。

func main() {
    c := make(chan os.Signal)
    signal.Notify(c, os.Interrupt)
    <-c
    log.Fatal("program interrupted")
}
$ go run main.go
Ctrl+C
2019/06/11 17:59:11 program interrupted
exit status 1

3 Server 優雅的終止

接下來我們使用如上 signal.Notify 結合 http.Server 的 Shutdown 方法實現服務優雅的終止。

如下代碼,Handler 與文章開始時的處理邏輯一樣,其會在2s後返回 hello。

創建一個 http.Server 實例,指定端口與 Handler。

聲明一個 processed chan,其用來保證服務優雅的終止後再退出主 goroutine。

新啓一個 goroutine,其會監聽 os.Interrupt 信號,一旦服務被中斷即調用服務的 Shutdown 方法,確保活躍連接的正常返回(本代碼使用的 Context 超時時間爲 3s,大於服務 Handler 的處理時間,所以不會超時)。

處理完成後,關閉 processed 通道,最後主 goroutine 退出。

代碼同時託管在 GitHub,歡迎關注(github.com/olzhy/go-excercises)。

var addr = flag.String("server addr"":8080""server address")

func main() {
    // handler
    handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        time.Sleep(2 * time.Second)
        fmt.Fprintln(w, "hello")
    })

    // server
    srv := http.Server{
        Addr:    *addr,
        Handler: handler,
    }

    // make sure idle connections returned
    processed := make(chan struct{})
    go func() {
        c := make(chan os.Signal, 1)
        signal.Notify(c, os.Interrupt)
        <-c

        ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
        defer cancel()
        if err := srv.Shutdown(ctx); nil != err {
            log.Fatalf("server shutdown failed, err: %v\n", err)
        }
        log.Println("server gracefully shutdown")

        close(processed)
    }()

    // serve
    err := srv.ListenAndServe()
    if http.ErrServerClosed != err {
        log.Fatalf("server not gracefully shutdown, err :%v\n", err)
    }

    // waiting for goroutine above processed
    <-processed
}
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/k9-aUMdcmSbjdG8YDgat8Q