> 作者:小黎的部落 | 日期:2026-10-30 | 系列:Rust 基础设施工具集

一、启动慢是服务的原罪

无论是服务端应用还是移动端 App,启动速度直接影响用户体验:

orca-preload 通过并行预热 + 依赖管理 + 健康检查三管齐下,让应用启动又快又稳。

二、核心设计

2.1 Loadable Trait — 声明式模块加载

pub trait Loadable {
    fn name(&self) -> &str;
    fn dependencies(&self) -> Vec<&str> { vec![] }
    async fn load(&self, progress: &LoadProgress) -> Result<(), String>;
}

每个模块只需实现这个 trait,引擎自动处理依赖顺序和并行加载。

2.2 依赖管理

struct DatabaseModule;
impl Loadable for DatabaseModule {
    fn name(&self) -> &str { "database" }
    fn dependencies(&self) -> Vec<&str> { vec![] }  // 无依赖
    async fn load(&self, progress: &LoadProgress) -> Result<(), String> {
        connect_to_db().await
    }
}

struct CacheModule;
impl Loadable for CacheModule {
    fn name(&self) -> &str { "cache" }
    fn dependencies(&self) -> Vec<&str> { vec!["database"] }  // 依赖数据库
    async fn load(&self, progress: &LoadProgress) -> Result<(), String> {
        init_cache().await
    }
}

引擎自动进行拓扑排序,确保 cache 在 database 之后加载,无依赖的模块并行加载。

2.3 进度跟踪

let engine = PreloadEngine::new()
    .register(DatabaseModule)
    .register(CacheModule)
    .register(ConfigModule)
    .on_progress(|name, phase, pct| {
        println!("[{}] {} - {}%", name, phase, pct);
    });

engine.load_all().await?;

输出示例:

[database] Connecting - 30%
[config] Loading - 50%
[database] Warming - 80%
[cache] Initializing - 60%
[database] Ready - 100%
[config] Ready - 100%
[cache] Ready - 100%

2.4 健康检查

let health = HealthCheck::new()
    .with_timeout(Duration::from_secs(5))
    .add_check("database", || check_db())
    .add_check("redis", || check_redis());

let results = health.run_all().await;
for (name, status) in results {
    match status {
        HealthStatus::Healthy => println!("{}: OK", name),
        HealthStatus::Unhealthy(e) => println!("{}: FAIL - {}", name, e),
    }
}

三、实战:服务端 Graceful Startup

#[tokio::main]
async fn main() {
    // 1. 并行加载所有模块
    let engine = PreloadEngine::new()
        .register(DatabaseModule)
        .register(CacheModule)
        .register(ConfigModule)
        .register(MqModule);

    engine.load_all().await.expect("模块加载失败");

    // 2. 健康检查
    engine.health_check().await.expect("健康检查失败");

    // 3. 所有模块就绪,开始接收流量
    start_http_server().await;
}

四、与其他方案对比

方案并行加载依赖管理健康检查进度跟踪
手动 init❌❌❌❌
Android App Startup✅✅❌❌
orca-preload✅✅✅✅

五、总结

orca-preload 把启动优化从「手工编排」变成了「声明式配置」。你只需要告诉引擎每个模块加载什么、依赖谁,剩下的并行调度、进度跟踪、健康检查全部自动完成。

六、下载

下载 orca-preload.tar.gz (10.1 KB)

← 返回文章列表