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 ?? v1.20.3 via ?? base took 1m 40.7s
? go run main.go
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env: export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode)
[GIN-debug] GET / --> main.main.func1 (3 handlers)
^C2023/06/18 17:50:48 Shutdown Server ...
[GIN] 2023/06/18 - 17:50:48 | 200 | 5.001188625s | 127.0.0.1 | GET "/"
2023/06/18 17:50:49 Server exiting
Code/go/shutdown_demo via ?? v1.20.3 via ?? base took 18.8s
?
訪問:http://127.0.0.1:8080/

運行之后訪問:http://127.0.0.1:8080/,然后 CTRL C 立即停止關閉服務,
會發現控制臺中 Shutdown Server ... 會先列印出來,然后是200 請求回應 ,最后 Server exiting 列印出來,
所以 Shutdown 會把未處理完的請求,處理完成后再關閉服務,
如果不使用 Shutdown ,程式會立即退出,
友好的重啟
程式在運行,一個重啟的命令,會fork 一個子行程,在這個時間點之前,沒有處理完的請求,由原來的父行程處理,從這個時間點之后,新來的請求,由 fork的子行程處理,等到父行程處理完成后,子行程就完全管理的Web服務,就實作了更加友好的重啟,
使用 fvbock/endless 來替換默認的 ListenAndServe啟動服務來實作,
當你的專案是使用類似supervisor的軟體管理行程時就不適用這種方式,
package main
import (
"log"
"net/http"
"time"
"github.com/fvbock/endless"
"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)
//}
// 默認endless服務器會監聽下列信號:
// syscall.SIGHUP,syscall.SIGUSR1,syscall.SIGUSR2,syscall.SIGINT,syscall.SIGTERM和syscall.SIGTSTP
// 接收到 SIGHUP 信號將觸發`fork/restart` 實作優雅重啟(kill -1 pid會發送SIGHUP信號)
// 接收到 syscall.SIGINT或syscall.SIGTERM 信號將觸發優雅關機
// 接收到 SIGUSR2 信號將觸發HammerTime
// SIGUSR1 和 SIGTSTP 被用來觸發一些用戶自定義的hook函式
// ListenAndServe監聽TCP網路地址addr,然后呼叫Serve處理程式來處理傳入連接上的請求,
// 處理程式通常為nil,在這種情況下使用DefaultServeMux,
if err := endless.ListenAndServe(":8080", router); err != nil {
log.Fatalf("listen: %s\n", err)
}
log.Println("Server exiting")
}
更多請訪問:https://github.com/fvbock/endless
本文來自博客園,作者:尋月隱君,轉載請注明原文鏈接:https://www.cnblogs.com/QiaoPengjun/p/17489629.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/555501.html
標籤:其他
下一篇:返回列表
