feat(api): 接进程 ctx 并停止启动异步链路
API 只装配 HTTP 入口。SetRouter 增加 ctx,删除 Outbox 轮询、Timeline 消费者与三个通知消费者的启动,改调 StartNotificationSubscriber。 SSEHub 记录进程 ctx。ctx 结束时 SSEHandler 主动断开。Shutdown 只关空闲连接、不取消在途请求,而 SSE 响应永不结束。少了这条路径,每次停机都要耗满 10 秒超时。 cmd/main 改用 signal.NotifyContext 与 http.Server。ListenAndServe 放进 goroutine,主协程等信号或启动失败,再以 10 秒上界 Shutdown,超时才 Close 兜底。 router_test 适配新签名,并新增用例守住四条通知路由仍注册。
This commit is contained in:
@@ -2,6 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"feedsystem_video_go/internal/auth"
|
||||
"feedsystem_video_go/internal/config"
|
||||
"feedsystem_video_go/internal/db"
|
||||
@@ -10,8 +11,11 @@ import (
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/observability"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
@@ -100,10 +104,47 @@ func main() {
|
||||
defer pprofServer.Close()
|
||||
}
|
||||
|
||||
// 进程生命周期:SIGINT/SIGTERM 后先停止接收新请求,再等在途请求结束。
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
// 设置路由
|
||||
r := apphttp.SetRouter(sqlDB, cache, rmq)
|
||||
log.Printf("Server is running on port %d", cfg.Server.Port)
|
||||
if err := r.Run(":" + strconv.Itoa(cfg.Server.Port)); err != nil {
|
||||
log.Fatalf("Failed to run server: %v", err)
|
||||
r := apphttp.SetRouter(ctx, sqlDB, cache, rmq)
|
||||
srv := &http.Server{
|
||||
Addr: ":" + strconv.Itoa(cfg.Server.Port),
|
||||
Handler: r,
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
// ListenAndServe 在 goroutine 里跑,主协程负责等待信号或启动失败。
|
||||
serverErr := make(chan error, 1)
|
||||
go func() {
|
||||
log.Printf("Server is running on port %d", cfg.Server.Port)
|
||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
serverErr <- err
|
||||
}
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-serverErr:
|
||||
log.Printf("Failed to run server: %v", err)
|
||||
stop()
|
||||
_ = srv.Close()
|
||||
return
|
||||
case <-ctx.Done():
|
||||
}
|
||||
|
||||
// 恢复默认信号处理:第二次 Ctrl-C 立刻强杀,而不是卡在 Shutdown 里。
|
||||
stop()
|
||||
|
||||
log.Printf("API shutting down...")
|
||||
// SSE 长连接由 SSEHub 在 ctx 取消时主动断开,所以这里等的是普通在途请求。
|
||||
// 超时后 Close 兜底:不能因为个别连接不返回就永远不退出。
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||
log.Printf("API graceful shutdown failed (forcing close): %v", err)
|
||||
_ = srv.Close()
|
||||
}
|
||||
log.Printf("API stopped")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user