// Package startup 提供服务启动时的组件初始化控制 // 各服务可以按需初始化所需组件,避免不必要的资源占用 package startup import ( "context" "sync" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/glog" ) // Components 组件配置 type Components struct { Consul bool // Consul 服务注册发现(所有服务都需要) Jaeger bool // Jaeger 链路追踪(所有服务都需要) Redis bool // Redis 缓存 RabbitMQ bool // RabbitMQ 消息队列 MongoDB bool // MongoDB 数据库 RAGFlow bool // RAGFlow AI 客户端 ES bool // Elasticsearch } var ( initialized bool initOnce sync.Once components *Components ) // Init 初始化指定的组件 // 示例: // // bootstrap.Init(ctx, &bootstrap.Components{ // Consul: true, // Jaeger: true, // Redis: true, // RabbitMQ: true, // }) func Init(ctx context.Context, c *Components) { initOnce.Do(func() { components = c initialized = true glog.Infof(ctx, "Bootstrap 初始化完成: %+v", c) }) } // IsInitialized 检查是否已初始化 func IsInitialized() bool { return initialized } // GetComponents 获取组件配置 func GetComponents() *Components { if components == nil { // 默认配置:从配置文件读取 return loadFromConfig() } return components } // NeedRedis 是否需要 Redis func NeedRedis() bool { c := GetComponents() return c != nil && c.Redis } // NeedRabbitMQ 是否需要 RabbitMQ func NeedRabbitMQ() bool { c := GetComponents() return c != nil && c.RabbitMQ } // NeedMongoDB 是否需要 MongoDB func NeedMongoDB() bool { c := GetComponents() return c != nil && c.MongoDB } // NeedRAGFlow 是否需要 RAGFlow func NeedRAGFlow() bool { c := GetComponents() return c != nil && c.RAGFlow } // NeedES 是否需要 Elasticsearch func NeedES() bool { c := GetComponents() return c != nil && c.ES } // loadFromConfig 从配置文件加载组件配置 // 如果配置文件中没有 startup 配置,则默认全部启动 func loadFromConfig() *Components { ctx := context.Background() // 检查是否有 startup 配置节 startupCfg := g.Cfg().MustGet(ctx, "startup") if startupCfg.IsEmpty() { // 没有配置 startup,默认全部启动 glog.Debug(ctx, "未找到 startup 配置,默认启动所有组件") return &Components{ Consul: true, Jaeger: true, Redis: true, RabbitMQ: true, MongoDB: true, RAGFlow: true, ES: true, } } // 有配置则按配置来,未配置的项默认 true return &Components{ Consul: g.Cfg().MustGet(ctx, "startup.consul", true).Bool(), Jaeger: g.Cfg().MustGet(ctx, "startup.jaeger", true).Bool(), Redis: g.Cfg().MustGet(ctx, "startup.redis", true).Bool(), RabbitMQ: g.Cfg().MustGet(ctx, "startup.rabbitmq", true).Bool(), MongoDB: g.Cfg().MustGet(ctx, "startup.mongodb", true).Bool(), RAGFlow: g.Cfg().MustGet(ctx, "startup.ragflow", true).Bool(), ES: g.Cfg().MustGet(ctx, "startup.es", true).Bool(), } }