# Go 語言之 Shutdown 關機和fvbock/endless 重啟 Shutdown 源碼 ```go // Shutdown gracefully shuts down the server without interrupting any // active connections. ...
Go 語言之 Shutdown 關機和fvbock/endless 重啟
Shutdown 源碼
// 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.
func (srv *Server) Shutdown(ctx context.Context) error {
srv.inShutdown.Store(true)
srv.mu.Lock()
lnerr := srv.closeListenersLocked()
for _, f := range srv.onShutdown {
go f()
}
srv.mu.Unlock()
srv.listenerGroup.Wait()
pollIntervalBase := time.Millisecond
nextPollInterval := func() time.Duration {
// Add 10% jitter.
interval := pollIntervalBase + time.Duration(rand.Intn(int(pollIntervalBase/10)))
// Double and clamp for next time.
pollIntervalBase *= 2
if pollIntervalBase > shutdownPollIntervalMax {
pollIntervalBase = shutdownPollIntervalMax
}
return interval
}
timer := time.NewTimer(nextPollInterval())
defer timer.Stop()
for {
if srv.closeIdleConns() {
return lnerr
}
select {
case <-ctx.Done():
return ctx.Err()
case <-timer.C:
timer.Reset(nextPollInterval())
}
}
}
Shutdown 關機實操
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/gin-gonic/gin"
)
func main() {
// Default返回一個Engine實例,其中已經附加了Logger和Recovery中間件。
router := gin.Default()
// GET is a shortcut for router.Handle("GET", path, handlers).
router.GET("/", func(c *gin.Context) {
// Sleep暫停當前常式至少持續時間d。持續時間為負或為零將導致Sleep立即返回。
time.Sleep(5 * time.Second)
// String將給定的字元串寫入響應體。
c.String(http.StatusOK, "Welcome Gin Server")
})
// 伺服器定義運行HTTP伺服器的參數。Server的零值是一個有效的配置。
srv := &http.Server{
// Addr可選地以“host:port”的形式指定伺服器要監聽的TCP地址。如果為空,則使用“:http”(埠80)。
// 服務名稱在RFC 6335中定義,並由IANA分配
Addr: ":8080",
Handler: router,
}
go func() {
// 開啟一個goroutine啟動服務,如果不用 goroutine,下麵的代碼 ListenAndServe 會一直接收請求,處理請求,進入無限迴圈。代碼就不會往下執行。
// ListenAndServe監聽TCP網路地址srv.Addr,然後調用Serve來處理傳入連接上的請求。接受的連接配置為使TCP能保持連接。
// ListenAndServe always returns a non-nil error. After Shutdown or Close,
// the returned error is ErrServerClosed.
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err) // Fatalf 相當於Printf()之後再調用os.Exit(1)。
}
}()
// 等待中斷信號來優雅地關閉伺服器,為關閉伺服器操作設置一個5秒的超時
// make內置函數分配並初始化(僅)slice、map或chan類型的對象。
// 與new一樣,第一個參數是類型,而不是值。
// 與new不同,make的返回類型與其參數的類型相同,而不是指向它的指針
// Channel:通道的緩衝區用指定的緩衝區容量初始化。如果為零,或者忽略大小,則通道未被緩衝。
// 信號 Signal 表示操作系統信號。通常的底層實現依賴於操作系統:在Unix上是syscall.Signal。
quit := make(chan os.Signal, 1) // 創建一個接收信號的通道
// kill 預設會發送 syscall.SIGTERM 信號
// kill -2 發送 syscall.SIGINT 信號,Ctrl+C 就是觸發系統SIGINT信號
// kill -9 發送 syscall.SIGKILL 信號,但是不能被捕獲,所以不需要添加它
// signal.Notify把收到的 syscall.SIGINT或syscall.SIGTERM 信號轉發給quit
// Notify使包信號將傳入的信號轉發給c,如果沒有提供信號,則將所有傳入的信號轉發給c,否則僅將提供的信號轉發給c。
// 包信號不會阻塞發送到c:調用者必須確保c有足夠的緩衝空間來跟上預期的信號速率。對於僅用於通知一個信號值的通道,大小為1的緩衝區就足夠了。
// 允許使用同一通道多次調用Notify:每次調用都擴展發送到該通道的信號集。從集合中移除信號的唯一方法是調用Stop。
// 允許使用不同的通道和相同的信號多次調用Notify:每個通道獨立地接收傳入信號的副本。
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) // 此處不會阻塞
<-quit // 阻塞在此,當接收到上述兩種信號時才會往下執行
log.Println("Shutdown Server ...")
// 創建一個5秒超時的context
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// 5秒內優雅關閉服務(將未處理完的請求處理完再關閉服務),超過5秒就超時退出
// 關機將在不中斷任何活動連接的情況下優雅地關閉伺服器。
// Shutdown的工作原理是首先關閉所有打開的偵聽器,然後關閉所有空閑連接,然後無限期地等待連接返回空閑狀態,然後關閉。
// 如果提供的上下文在關閉完成之前過期,則shutdown返回上下文的錯誤,否則返回關閉伺服器的底層偵聽器所返回的任何錯誤。
// 當Shutdown被調用時,Serve, ListenAndServe和ListenAndServeTLS會立即返回ErrServerClosed。確保程式沒有退出,而是等待Shutdown返回。
// 關閉不試圖關閉或等待被劫持的連接,如WebSockets。如果需要的話,Shutdown的調用者應該單獨通知這些長壽命連接關閉,並等待它們關閉。
// 一旦在伺服器上調用Shutdown,它可能不會被重用;以後對Serve等方法的調用將返回ErrServerClosed。
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Server Shutdown: ", err)
}
log.Println("Server exiting")
}
運行
Code/go/shutdown_demo via