bootstrap

package
v0.2.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package bootstrap 定义组件化启动编排。

本文件提供组件化 API,替代旧的硬编码 Run(Config, userFn)。 组件化 API 让 metrics、tracing、NNS 等启动步骤可插拔、可替换、可测试。

旧 API Run(Config, userFn) 保留为兼容入口,内部委托至组件化实现。

Package bootstrap 提供 ekit 微服务的启动编排。

统一管理:Prometheus 指标 → OpenTelemetry 追踪 → NNS 服务注册/发现 → 健康检查 → 优雅关闭。

快速接入

1. 定义配置结构(嵌入 nacos.Bootstrap):

type AppConfig struct {
    Port    int             `yaml:"port"`
    Nacos   nacos.Bootstrap `yaml:"nacos"`
    Tracing tracing.Config  `yaml:"tracing"`
    // 业务配置...
}

2. 启动服务:

func main() {
    cfg, _ := config.LoadBootstrap[AppConfig]("dev")
    bootstrap.Run(bootstrap.Config{
        ServiceName: "my-service",
        Port:        cfg.Port,
        Nacos:       cfg.Nacos,
        Tracing:     &cfg.Tracing,
    }, func(app *bootstrap.App) error {
        h := server.New(server.WithHostPorts(fmt.Sprintf(":%d", cfg.Port)))
        app.AddResource("hertz", func(ctx context.Context) error { return h.Shutdown(ctx) })
        health.RegisterHealthRoutes(h)
        // 注册业务路由...
        return h.Run()
    })
}

多 Server 场景

启动多个 HTTP server,通过 AddResource 注册关闭函数(逆序执行):

bootstrap.Run(bootstrap.Config{
    ServiceName: "gateway",
    Nacos:       cfg.Nacos,
    DepServices: []string{"user-service", "order-service"},
}, func(app *bootstrap.App) error {
    admin := server.New(server.WithHostPorts(":8081"))
    gw := server.New(server.WithHostPorts(":8080"))

    app.AddResource("gateway", func(ctx context.Context) error { return gw.Shutdown(ctx) })
    app.AddResource("admin", func(ctx context.Context) error { return admin.Shutdown(ctx) })

    go admin.Run()
    return gw.Run()
})

启动顺序

  1. Prometheus 指标注册
  2. OpenTelemetry 追踪初始化(可选)
  3. NNS 客户端初始化 + 服务注册(可选)
  4. 创建 App,执行 userFn(app)
  5. 监听 SIGINT/SIGTERM 信号
  6. 优雅关闭(App 资源 → 追踪 flush → NNS 注销)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Run

func Run(cfg Config, userFn func(*App) error) error

Run 启动服务,阻塞直到收到关闭信号或 userFn 返回。

这是兼容入口,内部委托至组件化 Bootstrapper。 推荐新代码直接使用 New(opts...).Run(userFn) 以获得更灵活的组件组合能力。

执行顺序:

  1. Prometheus 指标注册
  2. OpenTelemetry 追踪初始化(可选)
  3. NNS 初始化 + 服务注册(当 DepServices 或 Nacos.ServiceName 非空时)
  4. 创建 App,调用 userFn(app) 启动用户服务
  5. 监听 SIGINT/SIGTERM 信号
  6. 优雅关闭

Types

type App

type App struct {
	// contains filtered or unexported fields
}

App 是应用生命周期管理器,统一管理资源注册、后台任务和优雅关闭。

用法:

app := bootstrap.NewApp(shutdownMgr)
app.AddResource("db", db.Close)
app.GoBackground("poller", func(ctx context.Context) { ... })
// shutdown 时自动按注册逆序关闭所有资源和等待后台任务退出

func NewApp

func NewApp(mgr *shutdown.Manager) *App

NewApp 创建应用生命周期管理器。

func (*App) AddResource

func (a *App) AddResource(name string, closer func(context.Context) error)

AddResource 注册需要在关闭时释放的资源。 name 用于日志标识,closer 是关闭函数。

func (*App) Context

func (a *App) Context() context.Context

Context 返回应用的根 context,可传递给后台任务。

func (*App) GoBackground

func (a *App) GoBackground(name string, fn func(ctx context.Context))

GoBackground 启动一个带 panic recovery 的后台 goroutine。 关闭时通过 ctx 取消信号通知退出,并等待所有后台任务完成。

func (*App) RequestShutdown

func (a *App) RequestShutdown()

RequestShutdown 请求应用进入关闭流程:取消根 context,解除 userFn 中 `<-app.Context().Done()` 的阻塞,使其返回并触发 shutdown.Manager 的优雅 关闭序列。幂等;在关闭序列中再次调用是安全的(cancel 本身幂等)。 典型用途见 lifecycle.App.RequestShutdown。

func (*App) SetWaitTimeout

func (a *App) SetWaitTimeout(d time.Duration)

SetWaitTimeout 设置 GoBackground goroutine 的 drain 超时。 超时后 wg.Wait 被跳过,日志警告仍在运行的 goroutine 数量。 默认 30s;传 0 禁用超时(无限等待,仅在确信所有 goroutine 会自行退出时使用)。

type Bootstrapper

type Bootstrapper struct {
	// contains filtered or unexported fields
}

Bootstrapper 是组件化应用编排器。

通过函数选项配置启动组件,支持按需组合 metrics、tracing、NNS 等能力。 本地开发和测试场景可不添加任何外部依赖组件。

示例:

b, err := bootstrap.New(
    bootstrap.WithServiceName("my-service"),
    bootstrap.WithMetrics(),
    bootstrap.WithTracing(tracing.Config{Endpoint: "otel:4317"}),
    bootstrap.WithNNS(nacosCfg, 8080, []string{"dep-service"}),
)
if err != nil { log.Fatal(err) }
b.Run(func(app *bootstrap.App) error {
    h := server.New(server.WithHostPorts(":8080"))
    app.AddResource("hertz", h.Shutdown)
    return h.Run()
})

func New

func New(opts ...BootstrapperOption) (*Bootstrapper, error)

New 创建 Bootstrapper 实例。

func (*Bootstrapper) Run

func (b *Bootstrapper) Run(userFn func(*App) error) error

Run 启动服务,阻塞直到收到关闭信号或 userFn 返回。

执行顺序:

  1. 创建 shutdown.Manager 和 App
  2. 按注册顺序初始化所有 Component
  3. 调用 userFn(app) 启动用户服务
  4. 监听 SIGINT/SIGTERM
  5. 优雅关闭

type BootstrapperOption

type BootstrapperOption func(*Bootstrapper)

BootstrapperOption 配置 Bootstrapper。

func WithComponent

func WithComponent(c Component) BootstrapperOption

WithComponent 添加自定义组件。

func WithMetrics

func WithMetrics() BootstrapperOption

WithMetrics 添加 Prometheus 指标注册组件。 serviceName 在 New() 应用完全部选项后统一回填,与 WithServiceName 的 调用顺序无关。

func WithNNS

func WithNNS(nacosCfg nacospkg.Bootstrap, port int, depServices []string, nnsOpts ...nns.NNSOption) BootstrapperOption

WithNNS 添加 NNS 服务治理组件。

nacosCfg 是 Nacos 连接配置,port 是服务注册端口(0 则跳过注册), depServices 是依赖服务列表,nnsOpts 传递给 nns.New。

func WithRequiredNNS

func WithRequiredNNS(nacosCfg nacospkg.Bootstrap, port int, depServices []string, nnsOpts ...nns.NNSOption) BootstrapperOption

WithRequiredNNS 添加 NNS 组件并声明为强依赖: NNS 初始化失败时启动失败(fail-fast),而非默认的告警继续。

func WithServiceName

func WithServiceName(name string) BootstrapperOption

WithServiceName 设置服务名称(必填)。

func WithShutdownHook

func WithShutdownHook(name string, hook func(ctx context.Context) error) BootstrapperOption

WithShutdownHook 添加自定义关闭钩子。

func WithShutdownTimeout

func WithShutdownTimeout(d time.Duration) BootstrapperOption

WithShutdownTimeout 设置优雅关闭超时,默认 10 秒。

func WithTracing

func WithTracing(cfg tracing.Config) BootstrapperOption

WithTracing 添加 OpenTelemetry 追踪组件。

type Component

type Component interface {
	// Name 返回组件标识,用于日志。
	Name() string
	// Init 执行组件初始化,可通过 app 和 mgr 注册资源和关闭钩子。
	Init(ctx context.Context, app *App, mgr *shutdown.Manager) error
}

Component 是可插拔的启动组件接口。 每个组件负责一项启动任务(如指标注册、追踪初始化、NNS 注册等), 并可通过 mgr 注册关闭钩子。

type Config

type Config struct {
	// ServiceName 服务名称,用于 metrics 标签和 Nacos 注册。
	ServiceName string

	// Port 服务端口,用于 Nacos 实例注册。
	Port int

	// Nacos Nacos 连接配置。
	// 如果为空,跳过 Nacos 相关功能。
	Nacos nacospkg.Bootstrap

	// DepServices 依赖的服务名称列表(Nacos DataId)。
	// 非空时自动初始化 NNS 客户端。
	DepServices []string

	// Tracing OpenTelemetry 配置。为 nil 时跳过追踪初始化。
	Tracing *tracing.Config

	// ShutdownTimeout 优雅关闭总超时,默认 10 秒。
	ShutdownTimeout time.Duration
}

Config 是启动编排的配置。

type MetricsComponent

type MetricsComponent struct {
	// ServiceName 用于 Prometheus 指标中的 service 标签。
	ServiceName string
}

MetricsComponent Prometheus 指标注册组件。 serviceName 由 Bootstrapper.New 在应用选项解析后统一填充, 组件自身不感知 Bootstrapper 内部结构。

func (*MetricsComponent) Init

Init 注册 Prometheus 指标。

func (*MetricsComponent) Name

func (c *MetricsComponent) Name() string

Name 返回组件名称。

type NNSComponent

type NNSComponent struct {
	NacosCfg    nacos.Bootstrap
	Port        int
	DepServices []string
	NSNOpts     []nns.NNSOption
	// Required 为 true 时,NNS 初始化失败将返回错误(fail-fast),
	// 触发 Bootstrapper 的回滚与启动失败;为 false(默认)时仅告警并
	// 继续启动(服务对 NNS 为软依赖)。
	Required bool
}

NNSComponent NNS 服务治理组件,负责 NNS 客户端初始化和服务注册。

func (*NNSComponent) Init

func (c *NNSComponent) Init(ctx context.Context, _ *App, mgr *shutdown.Manager) error

Init 初始化 NNS 客户端并注册服务实例。

func (*NNSComponent) Name

func (c *NNSComponent) Name() string

Name 返回组件名称。

type ShutdownHookComponent

type ShutdownHookComponent struct {
	ComponentName string
	Hook          func(ctx context.Context) error
}

ShutdownHookComponent 通用关闭钩子组件,用于注册自定义资源释放逻辑。

func (*ShutdownHookComponent) Init

Init 将关闭钩子注册到 shutdown.Manager。

func (*ShutdownHookComponent) Name

func (c *ShutdownHookComponent) Name() string

Name 返回组件名称。

type TracingComponent

type TracingComponent struct {
	Config tracing.Config
}

TracingComponent OpenTelemetry 追踪初始化组件。

func (*TracingComponent) Init

func (c *TracingComponent) Init(_ context.Context, _ *App, mgr *shutdown.Manager) error

Init 初始化 OpenTelemetry 追踪,并注册 shutdown 钩子。

func (*TracingComponent) Name

func (c *TracingComponent) Name() string

Name 返回组件名称。

type WorkerManager

type WorkerManager struct {
	// contains filtered or unexported fields
}

WorkerManager 管理一组周期性后台任务。

用法:

wm := bootstrap.NewWorkerManager(ctx)
wm.AddTicker("timeout-checker", 60*time.Second, func(ctx context.Context) {
    buildSvc.CheckBuildTimeout(ctx)
    deploySvc.CheckDeployTimeout(ctx)
})
wm.AddTicker("metrics-reporter", 30*time.Second, func(ctx context.Context) {
    common.ReportQueueMetrics(ctx)
})
// ctx 取消时所有 worker 自动退出

func NewWorkerManager

func NewWorkerManager(ctx context.Context) *WorkerManager

NewWorkerManager 创建后台任务管理器。 ctx 取消或 Close() 调用时所有任务自动退出。

func (*WorkerManager) AddOnce

func (w *WorkerManager) AddOnce(name string, fn func(ctx context.Context))

AddOnce 注册一个一次性任务,在后台执行。

func (*WorkerManager) AddTicker

func (w *WorkerManager) AddTicker(name string, interval time.Duration, fn func(ctx context.Context))

AddTicker 注册一个周期性任务,按 interval 间隔执行 fn。 ctx 取消时自动退出。

func (*WorkerManager) Close

func (w *WorkerManager) Close()

Close 取消 context、阻止新任务注册并等待所有已启动的任务退出。 多次调用是安全的。

func (*WorkerManager) Wait

func (w *WorkerManager) Wait()

Wait 等待所有任务退出。

Directories

Path Synopsis
Package healthz 提供 ekit 应用健康检查 helper,让业务注册多个 check 项(DB / Redis / 上游依赖等),/healthz endpoint 一次调起,全部通过返 200, 任一失败返 503。
Package healthz 提供 ekit 应用健康检查 helper,让业务注册多个 check 项(DB / Redis / 上游依赖等),/healthz endpoint 一次调起,全部通过返 200, 任一失败返 503。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL