feat(app): 增强优雅停机逻辑与请求处理
- 新增 inFlight 原子计数器以跟踪当前处理的请求数 - 更新 initiateGracefulShutdown 方法,支持每秒检测在途请求,优化停机时长 - 修改日志信息,提供更清晰的停机状态反馈 - 更新 DrainTimeout 注释,明确最长等待时长与检测机制
This commit is contained in:
+25
-4
@@ -40,8 +40,9 @@ type Application struct {
|
||||
*http.Server
|
||||
http.Handler
|
||||
shuttingDown atomic.Bool // 停机标志,置为 true 后新请求立即返回 503
|
||||
inFlight atomic.Int64 // 当前正在处理的请求数(不含已返回 503 的)
|
||||
shutdownOnce sync.Once // 保证多路触发(信号/关窗口)只执行一次
|
||||
DrainTimeout time.Duration // 返回 503 后等 nginx 切流的时长,默认 5s
|
||||
DrainTimeout time.Duration // 返回 503 后等 nginx 切流的最长时长,默认 5s(每 1s 检测在途请求,为 0 则立即进入 Shutdown)
|
||||
ShutdownTimeout time.Duration // 等在途请求完成的最长时间,默认 30s
|
||||
}
|
||||
|
||||
@@ -51,17 +52,37 @@ func (that *Application) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
http.Error(w, "Service Unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
that.inFlight.Add(1)
|
||||
defer that.inFlight.Add(-1)
|
||||
that.handler(w, req)
|
||||
}
|
||||
|
||||
// initiateGracefulShutdown 触发优雅停机,通过 sync.Once 保证多路触发只执行一次。
|
||||
// drain: 返回 503 后等待上游(nginx)完成流量切换的时长。
|
||||
// drain: 返回 503 后等待上游(nginx)完成流量切换的最长时长,每 1s 检测一次在途请求数,
|
||||
// 若为 0 则立即进入 Shutdown,避免无谓等待。
|
||||
// shutdown: 等待在途请求完成的最长时间。
|
||||
func (that *Application) initiateGracefulShutdown(drain, shutdown time.Duration) {
|
||||
that.shutdownOnce.Do(func() {
|
||||
that.shuttingDown.Store(true)
|
||||
that.Log.Infof("优雅停机:新请求已返回 503,等 %v 让 nginx 完成流量切换...", drain)
|
||||
time.Sleep(drain)
|
||||
that.Log.Infof("优雅停机:新请求已返回 503,最多等 %v 让 nginx 完成流量切换(每秒检测在途请求)...", drain)
|
||||
|
||||
// 每秒检测一次,若无在途请求立即停机,否则最多等满 drain
|
||||
tick := time.NewTicker(1 * time.Second)
|
||||
defer tick.Stop()
|
||||
deadline := time.Now().Add(drain)
|
||||
for {
|
||||
if n := that.inFlight.Load(); n == 0 {
|
||||
that.Log.Infof("无在途请求,立即进入 Shutdown")
|
||||
break
|
||||
} else if time.Now().After(deadline) {
|
||||
that.Log.Infof("drain 等待到达上限 %v,仍有 %d 个在途请求,强制进入 Shutdown", drain, n)
|
||||
break
|
||||
} else {
|
||||
that.Log.Infof("drain 等待中,当前在途请求数=%d", n)
|
||||
}
|
||||
<-tick.C
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), shutdown)
|
||||
defer cancel()
|
||||
that.Log.Infof("停止接受新连接,等进行中请求完成(最多 %v)...", shutdown)
|
||||
|
||||
Reference in New Issue
Block a user