@@ -104,6 +104,10 @@ var ServerHandlerSingleton *ServerHandler
104104var (
105105 activeRequestTaskGoroutines int64
106106 maxRequestTaskGoroutines int64 = 50 // 大幅降低最大允许的 RequestTask goroutine 数量
107+
108+ // goroutine清理控制变量
109+ lastGoroutineCleanupTime time.Time
110+ lastCleanupMutex sync.Mutex
107111)
108112
109113type ServerHandler struct {
@@ -220,17 +224,33 @@ func (s *ServerHandler) RequestTask(h *pb.Host, stream pb.ServerService_RequestT
220224 current := activeRequestTaskGoroutines
221225 total := int64 (runtime .NumGoroutine ())
222226
223- // 如果总 goroutine 数量过多,先尝试强制清理
224- if total > 400 {
225- log .Printf ("警告:总 goroutine 数量过多 (%d),尝试强制清理" , total )
226- cleaned := ForceCleanupStaleConnections ()
227- if cleaned > 0 {
228- log .Printf ("强制清理了 %d 个连接,当前 goroutine 数量: %d" , cleaned , runtime .NumGoroutine ())
229- }
230- // 清理后仍然过多,拒绝新连接
231- if runtime .NumGoroutine () > 500 {
232- log .Printf ("清理后 goroutine 数量仍过多 (%d),拒绝新的 RequestTask 连接" , runtime .NumGoroutine ())
233- return - 1
227+ // 提高阈值并减少清理频率,避免频繁日志输出
228+ if total > 600 { // 提高阈值从400到600
229+ // 使用包级变量控制清理频率,避免每次连接都清理
230+ lastCleanupMutex .Lock ()
231+ now := time .Now ()
232+ // 至少间隔30秒才进行一次清理
233+ if now .Sub (lastGoroutineCleanupTime ) > 30 * time .Second {
234+ lastGoroutineCleanupTime = now
235+ lastCleanupMutex .Unlock ()
236+
237+ log .Printf ("警告:总 goroutine 数量过多 (%d),尝试强制清理" , total )
238+ cleaned := ForceCleanupStaleConnections ()
239+ if cleaned > 0 {
240+ log .Printf ("强制清理了 %d 个连接,当前 goroutine 数量: %d" , cleaned , runtime .NumGoroutine ())
241+ }
242+
243+ // 清理后仍然过多,拒绝新连接
244+ if runtime .NumGoroutine () > 800 { // 提高拒绝阈值
245+ log .Printf ("清理后 goroutine 数量仍过多 (%d),拒绝新的 RequestTask 连接" , runtime .NumGoroutine ())
246+ return - 1
247+ }
248+ } else {
249+ lastCleanupMutex .Unlock ()
250+ // 如果goroutine数量极高,直接拒绝
251+ if total > 800 {
252+ return - 1
253+ }
234254 }
235255 }
236256
0 commit comments