@@ -123,19 +123,28 @@ func main() {
123123 // 初始化Goroutine池,防止内存泄漏
124124 singleton .InitGoroutinePools ()
125125
126- initSystem ()
127-
128126 // 创建用于控制所有后台任务的context
129127 ctx , cancel := context .WithCancel (context .Background ())
130128 defer cancel ()
131- _ = ctx // 将来可能用于goroutine控制
129+ _ = ctx // 用于将来的goroutine控制
132130
133- // 启动所有服务
134- // 只在非BadgerDB模式下调用CleanMonitorHistory,BadgerDB模式下已经在initSystem中调用
135- if singleton .Conf .DatabaseType != "badger" {
136- singleton .CleanMonitorHistory ()
137- }
131+ // 【重要】提前启动HTTP服务器,避免前端502错误
132+ log .Printf ("正在提前启动HTTP服务器在端口 %d..." , singleton .Conf .HTTPPort )
133+ srv := controller .ServeWeb (singleton .Conf .HTTPPort )
134+ log .Printf ("HTTP服务器已创建,将在业务初始化完成后启动服务" )
135+
136+ // 异步初始化系统,避免阻塞HTTP服务器
137+ go func () {
138+ defer func () {
139+ if r := recover (); r != nil {
140+ log .Printf ("系统初始化goroutine panic恢复: %v" , r )
141+ }
142+ }()
143+ initSystem ()
144+ log .Printf ("系统初始化完成" )
145+ }()
138146
147+ // 启动RPC服务
139148 go rpc .ServeRPC (singleton .Conf .GRPCPort )
140149 serviceSentinelDispatchBus := make (chan model.Monitor )
141150
@@ -167,13 +176,23 @@ func main() {
167176 singleton .AlertSentinelStart ()
168177 }()
169178
170- log .Printf ("正在初始化ServiceSentinel..." )
171- singleton .NewServiceSentinel (serviceSentinelDispatchBus )
172- log .Printf ("ServiceSentinel初始化完成" )
179+ // 异步初始化ServiceSentinel,避免阻塞
180+ go func () {
181+ defer func () {
182+ if r := recover (); r != nil {
183+ log .Printf ("ServiceSentinel初始化goroutine panic恢复: %v" , r )
184+ }
185+ }()
173186
174- log .Printf ("正在创建HTTP服务器..." )
175- srv := controller .ServeWeb (singleton .Conf .HTTPPort )
176- log .Printf ("HTTP服务器创建完成" )
187+ log .Printf ("正在初始化ServiceSentinel..." )
188+ singleton .NewServiceSentinel (serviceSentinelDispatchBus )
189+ log .Printf ("ServiceSentinel初始化完成" )
190+
191+ // 只在非BadgerDB模式下调用CleanMonitorHistory
192+ if singleton .Conf .DatabaseType != "badger" {
193+ singleton .CleanMonitorHistory ()
194+ }
195+ }()
177196
178197 go func () {
179198 defer func () {
@@ -184,7 +203,8 @@ func main() {
184203 dispatchReportInfoTask ()
185204 }()
186205
187- log .Printf ("正在启动HTTP服务器在端口 %d..." , singleton .Conf .HTTPPort )
206+ log .Printf ("所有服务已启动,HTTP服务器将运行在端口 %d" , singleton .Conf .HTTPPort )
207+
188208 // 优雅关闭处理
189209 if err := graceful .Graceful (func () error {
190210 return srv .ListenAndServe ()
0 commit comments