Help us shape the future of Go! Take the 2026 Go Developer Survey

bootstrap

package module
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 12 Imported by: 0

README

bootstrap

应用生命周期引导——统一骨架/资源注册/优雅关停/健康检查

🌐 项目主页:https://oekit.github.io/ · 名称由来:Open Easy Kit(开源 · 易用 · 工具集合) 🤖 AI Agent:本仓规范与硬规则见 AGENTS.md;机器可读索引见 llms.txt(接口签名以源码为准)。

安装

go get github.com/oekit/bootstrap@v0.5.0

这个仓库做什么

bootstrap 是应用生命周期引导:bootstrap.Run 提供「初始化 → 运行 → 优雅关停」 的统一骨架——资源注册、goroutine 托管、关停顺序、超时兜底全部内建。

快速使用

import (
    "github.com/oekit/bootstrap"
    ekithertz "github.com/oekit/hertz/hertz"
)

bootstrap.Run(cfg, func(app *bootstrap.App) error {
    h := hertzserver.New(...)
    ekithertz.RunServer(app, "my-service", h)   // server 接入生命周期
    app.AddResource("db", func(ctx context.Context) error { return dbPool.Close() })
    app.GoBackground("worker", workerLoop)       // 托管后台 goroutine(panic 兜底)

    <-app.Context().Done() // ★ 长驻服务必须阻塞:返回即视为服务结束
    return nil
})

attach 模式

bootstrap.NewApp(mgr *shutdown.Manager) 是 attach 模式入口:只把生命周期 四阶段挂到调用方的 shutdown.Manager 上,不接管信号与 server——不调用 signal.Notify、不调用 h.Spin,SIGINT/SIGTERM 与服务启停由宿主负责。 适合宿主已有 Spin/OnShutdown 生命周期(如 hertz),只想补上「ctx 取消 + 资源关闭 + 后台任务 drain」的场景:

teardown := shutdown.New(30 * time.Second)
app := bootstrap.NewApp(teardown)
app.GoBackground("outbox", outbox.Run)
app.AddResource("redis", func(ctx context.Context) error { return rdb.Close() })
h.OnShutdown = append(h.OnShutdown, func(ctx context.Context) {
    teardown.Shutdown(ctx)
})
h.Spin()

四阶段顺序语义(job 名 app-lifecycle:{cancel,drain,close,wait}):

阶段 做什么
cancel 取消 app.Context(),通知 GoBackground 退出
drain 等待 Acquire 中的在途请求(shutdown.Manager.Drain)
close 逆序执行 app.AddResource 注册的 closer
wait 等待 app.GoBackground goroutine 退出(超时可配)

shutdown.Manager 按注册顺序执行 job(注册顺序 = 执行顺序):caller 在 NewApp 之前 mgr.Add 的任务先于四阶段执行;在 NewApp 之后 mgr.Add 的任务排到四阶段之后(错过 close 窗口,应用资源请改用 AddResource/GoBackground)。

健康检查

import "github.com/oekit/bootstrap/healthz"

healthz.RegisterCheck("db", pingDB)   // 多 check 并发探测、总超时、panic 隔离
code, body := healthz.Handle(ctx)      // 全通过 200,任一失败 503 + 详情

// Hertz 服务无需手写 handler:github.com/oekit/hertz 的 health 子包
// 提供 RegisterHealthRoutes(h),内部消费本包 Handle

语义要点

  • app.AddResource(name, closer):关停时按注册逆序释放
  • app.GoBackground(name, fn):托管后台 goroutine(panic 被 recover)
  • 时间关系(K8s):发现延迟 < preStop < server 最大延迟 < ExitWaitTime < terminationGracePeriod

边界

  • Hertz/Kitex 的 RunServer 接入本骨架;NNS 注册用 nnsc.RunWithLifecycle

矩阵总览(23 活跃模块,自动生成)

模块 内容 矩阵内依赖
pkg 微工具集 21 合 1(errors/bloomx/contextx/container/validator/stringx/slicex/enumx/convert/encoding/jsonrepair/httpjson/mathx/pathx/pagination/ptrx/timex/uidgen/cache/bufiox/strmap);cache(v0.4.0 起)含缓存接口 CacheAside + BatchGetter 批量能力(MGet)+ LocalCache/SingleFlightCache + cachetest 契约 + Checker;container(v0.9.0 起,收编原 collectionx)泛型容器 Set/Ring/Queue/SafeMap + Map(sync.Map 背书)/Slice(并发安全);timex/stringx(v0.7.0 起)时间段边界 BeginningOf/EndOf 七对(分/时/日/周/月/季/年,周起始显式参数)+ trie 多模式替换器 Replacer(最长匹配)/ NewMask 敏感词遮罩;singleflighttest(v0.8.0 起)singleflight 共享契约测试套件(internal 与 concurrency 双侧引用) —
concurrency 并发与流控原语(async/gopool/group/singleflight/progress/syncx/ratelimit/retry)+ window 滑动窗口 / breaker 自适应熔断(规范哨兵 ErrCircuitOpen)/ shedding CPU 自适应降载 / batch 攒批执行器(满条数/满字节/窗口去重)/ timewheel 单级时间轮 pkg
logx 统一日志门面(多后端可替换 + Sink + caller 归属)+ 优雅关停;桥接子包 hlog/hertzlog/kitexlog 为嵌套模块按需引入 —
core 应用基建件(governance 治理 schema / config 配置加载 + default/env/range/options tag 校验 / lifecycle 契约 / network IP 工具 / version) —
metrics Prometheus 门面 + 弹性指标族 core
tracing OpenTelemetry 追踪 + trace_id 真相源 logx
registry 注册发现核心 + Nacos 实现 + Nacos 配置源 + sdbridge core、logx
data 数据访问门面——复刻 ekit data/ 能力面:cache/rediscache/crud/distlock/gormx/redisx/timertask/cachetest 八子包 re-export(类型同一,实现住 pkg 与各子仓)+ cached 缓存读写编排(写后失效/事务提交后失效/查询缓存版本号失效/GetByIDs 批量点读 MGet 快路径/bloom 防穿透)+ twolevel 两级缓存与跨实例失效广播(v0.7.0 起本仓唯二非 re-export 实现);all/ 聚合模块已废弃 retract concurrency、gormx、logx、pkg、redisx、timertask
gormx SQL/GORM 全家——连接池增强、框架无关 CRUD Service、仓储(原 oekit/gorm,v0.3.0 更名) logx、pkg
redisx Redis 全家——客户端封装(根包)、分布式缓存 cache/、分布式锁 distlock、分布式限流 ratelimit(Lua 三态 + 故障本地兜底) concurrency、logx、pkg
etcdx etcd 全家——客户端封装(根包:生产默认值/Health 探活/Close(ctx) 幂等)、registry 注册发现实现(SPI 对接 registry/nacos 链路:Lease KeepAlive 注册 + 丢约指数退避自动重注册、prefix Watch 订阅推送、ConfigStore KV 配置监听)、distlock 分布式锁(Session+concurrency.Mutex 公平排队,接口与 redisx/distlock.Locker 同形可互换,可选无 etcd 降级放行) concurrency、core、logx、registry
httpx HTTP 客户端 + 负载均衡——服务发现/熔断(规范哨兵 ErrCircuitOpen)/重试/指标/OTel 透传/一致性哈希(权重感知虚拟副本) concurrency、core、logx、metrics、registry、tracing
network 轻量网络客户端——WebSocket/NATS/MQ 抽象、连接与流工具 concurrency、logx、tracing
timertask 分片定时任务(FNV-1a、心跳续约) concurrency、logx
middleware Hertz 自研标准中间件栈 + contrib 桥接 + hmw + SheddingMiddleware 自适应降载 concurrency、core、logx、metrics、pkg、registry、tracing
k8s Kubernetes 客户端封装——RESTConfig/Clientset/DynamicClient 构建(显式 kubeconfig → in-cluster 自动 → KUBECONFIG/~/.kube/config 逐级回退,QPS/Burst 限流默认 50/100)+ leaderelection 子包 Lease 选主简化封装(OnStartedLeading/OnStoppedLeading/OnNewLeader 回调,主备单活,仅要求 Lease CRUD 权限) logx
nns NNS 服务治理客户端——provider 无关发现/配置/实例缓存 concurrency、core、logx、registry
nns-endpoint NNS 端点工厂——per-service 熔断、换实例重试、gRPC 池 concurrency、core、httpx、logx、metrics、nns、registry
bootstrap 应用生命周期引导——bootstrap.Run 骨架 + healthz concurrency、logx
hertz Hertz 运行时集成——日志桥接、生命周期、SSE/health/metrics、适配器、OTel、crudh/validatorh/versionh(原 handler 微库收编) bootstrap、concurrency、core、gormx、logx、metrics、middleware、nns、pkg、registry、tracing
kitex Kitex 生态——日志桥接、治理热更、生命周期、BizError 桥接、kitexotel、istio(xDS 动态熔断,原 istio 微库收编) bootstrap、concurrency、core、logx、metrics、nns、pkg、registry
workflow 组合式流程编排——串行/并行/异步/条件分支 + Hook AOP concurrency、logx
kitex-examples Kitex echo 示例——client/server + IDL + 治理配置 bootstrap、concurrency、core、kitex、logx、metrics、nns、pkg、registry、tracing

依赖严格自底向上;微库已合并为 pkg,旧微库仓已删除。

本仓在矩阵中的位置与依赖见上表「矩阵内依赖」列。历史沿革:源自 ekit 单体库 (git.enjoye.top/enjoydream/ekit v0.34.0,冻结维护),2026-10 拆分为独立 module。

License

MIT — 见 LICENSE

Documentation

Overview

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

本文件保留组件接口与轻量组件;重量级组件(metrics/tracing/NNS) 位于嵌套 module:github.com/oekit/bootstrap/obs 与 github.com/oekit/bootstrap/nacos,以 BootstrapperOption 注入。

Package bootstrap 提供 oekit 微服务的启动编排——纯编排壳,零重依赖。

职责:App 生命周期(ctx/资源注册/后台任务)、组件化 Bootstrapper、 信号监听与优雅关闭、WorkerManager。

组件化接入

重量级能力以嵌套 module 形式提供,经 BootstrapperOption 函数注入:

import (
    "github.com/oekit/bootstrap"
    "github.com/oekit/bootstrap/nacos" // Nacos/NNS 注册(按需)
    "github.com/oekit/bootstrap/obs"   // Prometheus/OTel(按需)
)

b, _ := bootstrap.New(
    bootstrap.WithServiceName("my-service"),
    nacos.WithNNS(cfg.Nacos, cfg.Port, cfg.DepServices),
    obs.WithMetrics(),
    obs.WithTracing(tracing.Config{Endpoint: "otel:4317"}),
)
_ = b.Run(userFn)

第三方集成实现 Component 接口后经 WithComponent 注入即可。

多 Server 场景

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

app.AddResource("hertz", func(ctx context.Context) error { return h.Shutdown(ctx) })

attach 模式(NewApp)

bootstrap.NewApp(mgr *shutdown.Manager) 是 **attach 模式**入口:只把 app-lifecycle 四阶段挂到调用方的 shutdown.Manager 上,**不接管信号与 server**——不调用 signal.Notify、不调用 h.Spin,SIGINT/SIGTERM 与服务 启停由宿主负责。适合宿主已有 Spin/OnShutdown 生命周期(如 hertz), 只想补上「ctx 取消 + 资源关闭 + 后台任务 drain」的场景:

teardown := shutdown.New(30 * time.Second)
app := bootstrap.NewApp(teardown)
app.GoBackground("outbox", outbox.Run)
app.AddResource("redis", func(ctx context.Context) error { return rdb.Close() })
h.OnShutdown = append(h.OnShutdown, func(ctx context.Context) {
    teardown.Shutdown(ctx)
})
h.Spin()

四阶段 job 名为 app-lifecycle:{cancel,drain,close,wait},按注册顺序在 mgr.Shutdown 时执行;caller 自己 mgr.Add 的任务同样按注册顺序插入: NewApp 之前 Add 的排在四阶段前,之后 Add 的排在四阶段后。AddResource 的 closer 在 close 阶段逆序释放;GoBackground 的 goroutine 在 wait 阶段 被等待退出。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

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 创建应用生命周期管理器,挂到调用方传入的 shutdown.Manager 上(attach 模式)。

契约:NewApp 只做生命周期编排,**不接管信号与 server**——不调用 signal.Notify、不调用 h.Spin/RunServer;SIGINT/SIGTERM 与服务启停 一律由宿主(如 hertz.Server + OnShutdown)负责,宿主停机回调里再调 mgr.Shutdown 即可。

四阶段顺序语义:NewApp 立即向 mgr 注册 app-lifecycle:{cancel,drain,close,wait} 四个 job;shutdown.Manager 按 **注册顺序**执行,因此调用方在 NewApp **之前** mgr.Add 的任务先于四阶段执行, 在 NewApp **之后** mgr.Add 的任务排在四阶段之后。应用自身资源请用 AddResource/GoBackground(分别落在 close / wait 阶段),不要在 NewApp 之后 直接 mgr.Add(会排到 wait 之后,错过 close 窗口)。

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 是组件化应用编排器。

通过函数选项配置启动组件;重量级集成(Nacos/NNS、Prometheus/OTel) 位于嵌套 module,以 Option 函数形式注入,根包保持零重依赖:

b, err := bootstrap.New(
    bootstrap.WithServiceName("my-service"),
    nacos.WithNNS(nacosCfg, 8080, deps),   // github.com/oekit/bootstrap/nacos
    obs.WithMetrics(),                     // github.com/oekit/bootstrap/obs
    obs.WithTracing(tracing.Config{...}),
)
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) AddComponent

func (b *Bootstrapper) AddComponent(c Component)

AddComponent 追加启动组件(动态注入)。 导出以支持嵌套 module 与第三方实现注入,与 WithComponent 等价。

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 添加自定义组件——第三方集成注入的标准入口。

实现 Component 接口的任意类型都可通过本方法接入启动编排; 嵌套 module(bootstrap/nacos、bootstrap/obs)的 WithXxx 选项 内部即委托此方法。

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 秒。

type Component

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

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

type ServiceNameAware

type ServiceNameAware interface {
	SetServiceName(name string)
}

ServiceNameAware 需要感知服务名的组件实现此接口; New() 在应用完全部选项后统一回填(与 WithServiceName 的调用顺序无关)。 嵌套 module 中的组件实现它即可参与回填,根包无需感知具体组件类型。

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 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。
nacos module
obs module

Jump to

Keyboard shortcuts

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