Documentation
¶
Index ¶
- Variables
- func AddMessageQueueConsumer(messageQueue *config.MessageQueue)
- func AddMessageQueueProducer(messageQueue *config.MessageQueue)
- func AddSchedule(schedule config.ScheduleInfo)
- func CloseAllServices(ctx context.Context, baseConfig *config.BaseConfig) error
- func CloseServices(ctx context.Context) error
- func ExecuteAppHooks(ctx context.Context, phase AppHookPhase) error
- func GetMessageQueueConsumerList() []*config.MessageQueue
- func GetMessageQueueProducerList() []*config.MessageQueue
- func GetScheduleList() []config.ScheduleInfo
- func InitAllServices(ctx context.Context, baseConfig *config.BaseConfig) error
- func InitServices(ctx context.Context) error
- func RegisterAppHook(hook AppHook)
- func RegisterService(service Service) error
- func RegisterServiceHook(serviceName string, hook Hook)
- func ResetGlobalStateForTest()
- func SetInitConfig(cfg InitConfig)
- type AppHook
- type AppHookPhase
- type DependencyResolver
- type HealthChecker
- type Hook
- type HookPhase
- type InitConfig
- type ParallelInitializer
- type Service
- type ServiceRegistry
- func (r *ServiceRegistry) CloseService(ctx context.Context, name string) error
- func (r *ServiceRegistry) ExecuteAppHooks(ctx context.Context, phase AppHookPhase) error
- func (r *ServiceRegistry) ExecuteHooks(ctx context.Context, serviceName string, phase HookPhase) error
- func (r *ServiceRegistry) GetAllServices() map[string]Service
- func (r *ServiceRegistry) GetService(name string) (Service, bool)
- func (r *ServiceRegistry) GetServicesToInit(cfg *config.BaseConfig) []Service
- func (r *ServiceRegistry) GetState(name string) ServiceState
- func (r *ServiceRegistry) InitService(ctx context.Context, name string) error
- func (r *ServiceRegistry) Register(service Service) error
- func (r *ServiceRegistry) RegisterAppHook(hook AppHook)
- func (r *ServiceRegistry) RegisterHook(serviceName string, hook Hook)
- func (r *ServiceRegistry) SetState(name string, state ServiceState)
- type ServiceState
Constants ¶
This section is empty.
Variables ¶
var DefaultInitConfig = InitConfig{ MaxConcurrency: 4, Timeout: 30 * time.Second, RetryCount: 0, RetryInterval: time.Second, }
DefaultInitConfig 默认初始化配置
Functions ¶
func AddMessageQueueConsumer ¶
func AddMessageQueueConsumer(messageQueue *config.MessageQueue)
AddMessageQueueConsumer 添加消息队列消费者配置 将消息队列消费者配置添加到全局列表中,在服务启动时会自动初始化这些消费者 支持多种消息队列类型和交换机模式,提供灵活的异步处理能力
参数 messageQueue: 消息队列配置对象,包含队列名、交换机、路由键和处理函数等信息
功能特性: - 支持多个消费者并发处理 - 自动记录队列配置信息 - 提供详细的日志输出
使用示例:
AddMessageQueueConsumer(config.MessageQueue{
QueueName: "user.created",
ExchangeName: "user.events",
ExchangeType: "topic",
RoutingKey: "user.created",
Fun: handleUserCreated,
})
func AddMessageQueueProducer ¶
func AddMessageQueueProducer(messageQueue *config.MessageQueue)
AddMessageQueueProducer 添加消息队列发送者配置 将消息队列发送者配置添加到全局列表中,在服务启动时会自动初始化这些发送者 支持多种消息队列类型和交换机模式,提供灵活的消息发送能力
参数 messageQueue: 消息队列配置对象,包含队列名、交换机、路由键等信息
功能特性: - 支持多个发送者配置 - 自动记录队列配置信息 - 提供详细的日志输出
使用示例:
AddMessageQueueProducer(config.MessageQueue{
MQName: "default",
QueueName: "user.created",
ExchangeName: "user.events",
ExchangeType: "topic",
RoutingKey: "user.created",
})
func AddSchedule ¶
func AddSchedule(schedule config.ScheduleInfo)
AddSchedule 添加定时任务配置 将定时任务配置添加到全局列表中,在服务启动时会自动启动这些任务 基于robfig/cron库实现,支持标准的Cron表达式语法
参数 schedule: 定时任务配置对象,包含Cron表达式和执行函数
Cron表达式格式: - 秒 分 时 日 月 周 - 支持特殊表达式如 @every 30s, @hourly, @daily 等
功能特性: - 支持多个任务并发执行 - 自动错误恢复 - 详细的任务执行日志
使用示例:
AddSchedule(config.ScheduleInfo{
Cron: "0 0 * * *", // 每天凌晨执行
Cmd: cleanupOldFiles,
})
AddSchedule(config.ScheduleInfo{
Cron: "@every 5m", // 每5分钟执行
Cmd: healthCheck,
})
func CloseAllServices ¶
func CloseAllServices(ctx context.Context, baseConfig *config.BaseConfig) error
CloseAllServices 关闭所有已注册的服务
func CloseServices ¶
CloseServices 关闭所有服务 按依赖关系逆序关闭服务,确保依赖的服务最后关闭
func ExecuteAppHooks ¶
func ExecuteAppHooks(ctx context.Context, phase AppHookPhase) error
ExecuteAppHooks 执行全局注册中心中指定阶段的应用级钩子
func GetMessageQueueConsumerList ¶
func GetMessageQueueConsumerList() []*config.MessageQueue
GetMessageQueueConsumerList 获取消息队列消费者列表
func GetMessageQueueProducerList ¶
func GetMessageQueueProducerList() []*config.MessageQueue
GetMessageQueueProducerList 获取消息队列发送者列表
func InitAllServices ¶
func InitAllServices(ctx context.Context, baseConfig *config.BaseConfig) error
InitAllServices 初始化所有已注册的服务
func InitServices ¶
InitServices 初始化所有服务组件 这是服务初始化的核心函数,使用并行初始化机制
初始化流程: 1. 使用依赖解析器分析服务依赖关系 2. 按层级并行初始化服务
特性: - 自动解析服务依赖关系 - 同一层级的服务并行初始化 - 支持自定义服务扩展 - 提供初始化前后的钩子机制
错误处理: - 关键服务初始化失败会返回错误 - 详细的错误信息帮助快速定位问题
func RegisterServiceHook ¶
RegisterServiceHook 注册钩子到全局注册中心
func ResetGlobalStateForTest ¶ added in v1.0.6
func ResetGlobalStateForTest()
ResetGlobalStateForTest 清空全局注册中心中的应用钩子、服务、服务级钩子与状态,并重置消息队列/定时任务累积列表及并行初始化配置。 仅供单元测试在顺序执行场景下恢复干净全局状态使用;不要在生产代码中调用。
Types ¶
type AppHook ¶
type AppHook struct {
Phase AppHookPhase // 执行阶段
Priority int // 执行优先级(数值越小越先执行)
Name string // 钩子名称,用于日志
Fn func(ctx context.Context) error // 钩子函数
}
AppHook 应用级生命周期钩子
type AppHookPhase ¶
type AppHookPhase int
AppHookPhase 应用级钩子执行阶段 与服务级 HookPhase 区分,AppHookPhase 作用于整个应用生命周期
const ( AppBeforeInit AppHookPhase = iota // 应用初始化前(loadConfig 之后、initService 之前) AppAfterInit // 应用初始化后(所有服务初始化完成、HTTP 监听之前) AppOnReady // HTTP 服务就绪后(ListenAndServe 成功后) AppBeforeShutdown // 应用关闭前(收到信号后、CloseServices 之前) AppAfterShutdown // 应用关闭后(所有服务关闭完成、进程退出前) AppOnInitFailed // 启动失败时(任意初始化阶段出错时触发) )
type DependencyResolver ¶
type DependencyResolver struct {
// contains filtered or unexported fields
}
DependencyResolver 依赖解析器 负责解析服务之间的依赖关系,并生成按层级分组的初始化顺序
func NewDependencyResolver ¶
func NewDependencyResolver(services map[string]Service) *DependencyResolver
NewDependencyResolver 创建依赖解析器
func (*DependencyResolver) GetDependencyOrder ¶
func (r *DependencyResolver) GetDependencyOrder(serviceName string) ([]string, error)
GetDependencyOrder 获取单个服务的依赖初始化顺序(扁平化)
func (*DependencyResolver) Resolve ¶
func (r *DependencyResolver) Resolve() ([][]string, error)
Resolve 解析依赖关系,返回按层级分组的初始化顺序。 返回值 [][]string 中,每个内层数组是可以并行初始化的服务组。
执行流程: 1. 使用 DFS 检测循环依赖,发现环则返回错误 2. 构建入度表(每个服务依赖数)和邻接表(被依赖关系) 3. 使用 Kahn 算法逐层剥离入度为 0 的节点,按优先级排序后加入当前层 4. 每剥离一层,更新依赖它的服务的入度,直到所有服务处理完毕
func (*DependencyResolver) ValidateDependencies ¶
func (r *DependencyResolver) ValidateDependencies() map[string][]string
ValidateDependencies 验证所有依赖是否存在 返回缺失的依赖列表
type HealthChecker ¶
HealthChecker 健康检查接口(可选实现)
type Hook ¶
type Hook struct {
Phase HookPhase // 执行阶段
Priority int // 执行优先级(数值越小越先执行)
Fn func(ctx context.Context, serviceName string) error // 钩子函数
}
Hook 初始化钩子
type InitConfig ¶
type InitConfig struct {
MaxConcurrency int // 最大并发数(0表示不限制)
Timeout time.Duration // 单个服务初始化超时(0表示不限制)
RetryCount int // 失败重试次数
RetryInterval time.Duration // 重试间隔
}
InitConfig 初始化配置
type ParallelInitializer ¶
type ParallelInitializer struct {
// contains filtered or unexported fields
}
ParallelInitializer 并行初始化器
func NewParallelInitializer ¶
func NewParallelInitializer(registry *ServiceRegistry, cfg InitConfig) *ParallelInitializer
NewParallelInitializer 创建并行初始化器
func (*ParallelInitializer) Close ¶
func (p *ParallelInitializer) Close(ctx context.Context, baseConfig *config.BaseConfig) error
Close 按依赖层级逆序关闭所有已初始化的服务 ctx: 关闭上下文,可用于传递取消信号 baseConfig: 基础配置,用于筛选需要关闭的服务
执行流程: 1. 获取需要关闭的服务列表并构建服务映射 2. 解析依赖关系获取初始化层级(解析失败时降级为逐个关闭) 3. 按层级逆序(先关闭最外层依赖者,后关闭底层被依赖者) 4. 同一层级内使用 errgroup 并行关闭,层间串行 5. 单层关闭出错仅记录日志,不中断后续层的关闭
func (*ParallelInitializer) Init ¶
func (p *ParallelInitializer) Init(ctx context.Context, baseConfig *config.BaseConfig) error
Init 执行并行初始化 参数:
- ctx: 上下文
- baseConfig: 基础配置,用于判断哪些服务需要初始化
type Service ¶
type Service interface {
// Name 返回服务名称(唯一标识)
Name() string
// Priority 返回初始化优先级(数值越小越先初始化)
// 用于在同一层级内排序
Priority() int
// Dependencies 返回依赖的服务名称列表
// 依赖的服务会在当前服务之前初始化
Dependencies() []string
// ShouldInit 根据配置判断是否需要初始化
ShouldInit(cfg *config.BaseConfig) bool
// Init 执行初始化逻辑
Init(ctx context.Context) error
// Close 执行清理逻辑
Close(ctx context.Context) error
}
Service 服务接口定义 所有需要在应用启动时初始化的服务都应该实现此接口
type ServiceRegistry ¶
type ServiceRegistry struct {
// contains filtered or unexported fields
}
ServiceRegistry 服务注册中心 管理所有服务的注册、初始化和关闭,同时管理应用级生命周期钩子
func (*ServiceRegistry) CloseService ¶
func (r *ServiceRegistry) CloseService(ctx context.Context, name string) error
CloseService 关闭单个服务 ctx: 关闭上下文 name: 服务名称 返回值: 服务未注册或非就绪状态时静默返回 nil;关闭失败时返回错误
执行流程: 1. 查找服务并校验状态(未注册或非 StateReady 时跳过) 2. 执行 BeforeClose 阶段钩子(失败仅记录日志,不阻止关闭) 3. 调用服务的 Close 方法执行实际关闭(失败则返回错误) 4. 执行 AfterClose 阶段钩子(失败仅记录日志) 5. 将状态置为 StateClosed
func (*ServiceRegistry) ExecuteAppHooks ¶
func (r *ServiceRegistry) ExecuteAppHooks(ctx context.Context, phase AppHookPhase) error
ExecuteAppHooks 执行指定阶段的应用级钩子 按优先级(数值越小越先执行)顺序执行所有匹配阶段的钩子
执行流程: 1. 筛选匹配指定阶段的钩子 2. 按优先级排序 3. 依次执行,任一钩子失败则立即返回错误
func (*ServiceRegistry) ExecuteHooks ¶
func (r *ServiceRegistry) ExecuteHooks(ctx context.Context, serviceName string, phase HookPhase) error
ExecuteHooks 执行指定服务在指定阶段的所有钩子 ctx: 执行上下文 serviceName: 服务名称 phase: 钩子阶段(BeforeInit / AfterInit / BeforeClose / AfterClose) 返回值: 钩子按优先级排序后依次执行,任一失败则立即返回错误
func (*ServiceRegistry) GetAllServices ¶
func (r *ServiceRegistry) GetAllServices() map[string]Service
GetAllServices 获取所有已注册服务的快照副本 返回值: 服务名称到服务实例的映射(返回的是副本,修改不影响注册中心)
func (*ServiceRegistry) GetService ¶
func (r *ServiceRegistry) GetService(name string) (Service, bool)
GetService 根据名称查找已注册的服务 name: 服务名称(与 Service.Name() 返回值一致) 返回值: 服务实例和是否存在的标识
func (*ServiceRegistry) GetServicesToInit ¶
func (r *ServiceRegistry) GetServicesToInit(cfg *config.BaseConfig) []Service
GetServicesToInit 获取需要初始化的服务列表 cfg: 基础配置,用于调用各服务的 ShouldInit 方法判断是否需要初始化 返回值: 通过 ShouldInit 校验的服务切片
func (*ServiceRegistry) GetState ¶
func (r *ServiceRegistry) GetState(name string) ServiceState
GetState 获取指定服务的当前生命周期状态 name: 服务名称 返回值: 服务状态,未注册的服务返回 StateUninitialized
func (*ServiceRegistry) InitService ¶
func (r *ServiceRegistry) InitService(ctx context.Context, name string) error
InitService 初始化单个服务 ctx: 初始化上下文,可用于超时控制和取消 name: 服务名称(必须已通过 Register 注册) 返回值: 初始化失败时返回错误,已就绪或正在初始化时分别跳过或报错
执行流程: 1. 查找服务并校验当前状态(已就绪则跳过,初始化中则报错) 2. 将状态置为 StateInitializing 3. 执行 BeforeInit 阶段钩子(失败则置 StateFailed 并返回) 4. 调用服务的 Init 方法执行实际初始化(失败则置 StateFailed 并返回) 5. 执行 AfterInit 阶段钩子(失败则置 StateFailed 并返回) 6. 将状态置为 StateReady
func (*ServiceRegistry) Register ¶
func (r *ServiceRegistry) Register(service Service) error
Register 注册服务 参数:
- service: 要注册的服务
返回:
- error: 如果服务名称已存在则返回错误
func (*ServiceRegistry) RegisterAppHook ¶
func (r *ServiceRegistry) RegisterAppHook(hook AppHook)
RegisterAppHook 注册应用级生命周期钩子 参数:
- hook: 应用级钩子配置,包含阶段、优先级、名称和执行函数
func (*ServiceRegistry) RegisterHook ¶
func (r *ServiceRegistry) RegisterHook(serviceName string, hook Hook)
RegisterHook 注册钩子 参数:
- serviceName: 服务名称
- hook: 钩子配置
func (*ServiceRegistry) SetState ¶
func (r *ServiceRegistry) SetState(name string, state ServiceState)
SetState 设置指定服务的生命周期状态 name: 服务名称 state: 目标状态(StateUninitialized / StateInitializing / StateReady / StateFailed / StateClosed)
type ServiceState ¶
type ServiceState int
ServiceState 服务状态
const ( StateUninitialized ServiceState = iota // 未初始化 StateInitializing // 初始化中 StateReady // 就绪 StateFailed // 失败 StateClosed // 已关闭 )