Files
common/startup/startup.go

105 lines
2.5 KiB
Go

// 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()
return &Components{
Consul: !g.Cfg().MustGet(ctx, "consul").IsEmpty(),
Jaeger: !g.Cfg().MustGet(ctx, "jaeger").IsEmpty(),
Redis: !g.Cfg().MustGet(ctx, "redis").IsEmpty(),
RabbitMQ: !g.Cfg().MustGet(ctx, "rabbitmq").IsEmpty(),
MongoDB: !g.Cfg().MustGet(ctx, "mongo").IsEmpty(),
RAGFlow: !g.Cfg().MustGet(ctx, "ragflow").IsEmpty(),
ES: !g.Cfg().MustGet(ctx, "elasticsearch").IsEmpty(),
}
}