首页 > 解决方案 > 如何与其他东西一起启动火箭服务器?

问题描述

基本上我希望有一个进程同时处理多个事情(特别是希望有一个 http 端点来监视非 http 服务),但我似乎被 Rocket 所吸引,这取决于特定于 Rocket 的 tokio运行时,我没有看到如何解决这个问题。我曾考虑让 Rocket 成为主要入口点,而不是 tokio 的标准入口点,并从该运行时启动其他东西,但这通常看起来是错误的并且很脆弱,因为我可能会切换库。我曾考虑过使用 hyper 和 warp,我有点自信我可以让它们在这种情况下工作,但我想使用火箭,因为我在这个项目的其他地方使用它。我正在使用 0.5-rc01 版本。

从文档:

Rocket v0.5 uses the tokio runtime. The runtime is started for you if you use #[launch] or #[rocket::main], but you can still launch() a Rocket instance on a custom-built runtime by not using either attribute.

不幸的是,我找不到任何关于这个定制运行时有什么要求的进一步解释,也找不到任何不使用启动/主宏的示例。

这是我尝试使用的代码的简化版本:

#[rocket::get("/ex")]
async fn test() -> &'static str {
    "OK"
}

#[tokio::main]
async fn main() {
    tokio::spawn(async {
        let config = Config {
            port: 8001,
            address: std::net::Ipv4Addr::new(127, 0, 0, 1).into(),
            ..Config::debug_default()
        };

        rocket::custom(&config)
            .mount("/", rocket::routes![test])
            .launch()
            .await;
    });

    let start = Instant::now();
    let mut interval = interval_at(start, tokio::time::Duration::from_secs(5));

    loop {
        interval.tick().await;
        println!("Other scheduled work");
    }
}

当我按 CTRL-C 终止进程时,将打印以下内容:

^CWarning: Received SIGINT. Requesting shutdown.
Received shutdown request. Waiting for pending I/O...
Warning: Server failed to shutdown cooperatively.
   >> Server is executing inside of a custom runtime.
   >> Rocket's runtime is `#[rocket::main]` or `#[launch]`.
   >> Refusing to terminate runaway custom runtime.
Other scheduled work
Other scheduled work
Other scheduled work

我发现此文档解释说,如果您使用自定义运行时,您需要在关机时“合作”,但它没有解释合作需要什么。此外,在生成的线程中运行除了火箭之外的东西会导致 CTRL-C 像我通常预期的那样杀死进程,所以我认为这与火箭特别有关。我需要做什么才能真正终止该进程?

编辑:我放弃并改用经线,这要容易一千倍。我仍然很想知道用火箭做到这一点的正确方法,如果有人有建议,我会再试一次。

标签: rust-rocket

解决方案


如果我们在 Rocket.toml 中添加一个关闭配置,线程也会终止。

[default.shutdown]
ctrlc = false
signals = ["term", "hup"]

请参阅此处的 Rocket Shutdown 文档: https ://api.rocket.rs/v0.5-rc/rocket/config/struct.Shutdown.html#example


推荐阅读