Files
cellbot/internal/di/lifecycle.go

80 lines
1.7 KiB
Go
Raw Normal View History

package di
import (
"context"
"cellbot/internal/engine"
"cellbot/internal/protocol"
"cellbot/pkg/net"
"go.uber.org/fx"
"go.uber.org/zap"
)
// RegisterLifecycleHooks 注册应用生命周期钩子
func RegisterLifecycleHooks(
logger *zap.Logger,
eventBus *engine.EventBus,
dispatcher *engine.Dispatcher,
botManager *protocol.BotManager,
server *net.Server,
lc fx.Lifecycle,
) {
lc.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
logger.Info("=== Starting CellBot application ===")
// 启动事件总线
logger.Info("Starting event bus...")
eventBus.Start()
logger.Info("Event bus started")
// 启动分发器
logger.Info("Starting dispatcher...")
dispatcher.Start(ctx)
logger.Info("Dispatcher started")
// 启动所有机器人
if err := botManager.StartAll(ctx); err != nil {
logger.Error("Failed to start bots", zap.Error(err))
}
// 启动HTTP服务器
if err := server.Start(); err != nil {
logger.Error("Failed to start server", zap.Error(err))
return err
}
logger.Info("CellBot application started successfully")
return nil
},
OnStop: func(ctx context.Context) error {
logger.Info("Stopping CellBot application...")
// 停止HTTP服务器
if err := server.Stop(); err != nil {
logger.Error("Failed to stop server", zap.Error(err))
}
// 停止所有机器人
if err := botManager.StopAll(ctx); err != nil {
logger.Error("Failed to stop bots", zap.Error(err))
}
// 停止分发器
dispatcher.Stop()
// 停止事件总线
eventBus.Stop()
logger.Info("CellBot application stopped successfully")
return nil
},
})
}
// Lifecycle 生命周期管理选项
var Lifecycle = fx.Options(
fx.Invoke(RegisterLifecycleHooks),
)