热更新

自动重新加载开发服务器

在开发过程中,让cargo在更改时自动重新编译代码会非常方便。 这可以通过使用cargo-watch来完成。 因为actix应用程序通常将绑定到端口以侦听传入的HTTP请求,所以将其与listenfd crate和systemfd实用程序结合使用以确保socket在应用程序编译和重新加载时保持打开状态是有意义的。

systemfd将打开一个socket,并将其传递给cargo-watch,它将监听更改,然后调用编译器并运行actix应用。然后,actix应用程序将使用listenfd来拾取systemfd打开的socket。

Binaries Necessary 必要的二进制文件

为了获得热更新的体验,您需要安装cargo-watchsystemfd。两者都是用Rust编写的,可以与cargo install一起安装:

cargo install systemfd cargo-watch

代码变更

另外,您需要稍微修改一下actix应用程序,以便它可以使用systemfd打开的外部socket。将listenfd依赖项添加到您的应用程序:

[dependencies]
listenfd = "0.3"

然后修改您的服务器代码以仅调用bind作为fallback:

use actix_web::{web, App, HttpRequest, HttpServer, Responder};
use listenfd::ListenFd;

async fn index(_req: HttpRequest) -> impl Responder {
    "Hello World!"
}

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    let mut listenfd = ListenFd::from_env();
    let mut server = HttpServer::new(|| App::new().route("/", web::get().to(index)));

    server = if let Some(l) = listenfd.take_tcp_listener(0).unwrap() {
        server.listen(l)?
    } else {
        server.bind("127.0.0.1:3000")?
    };

    server.run().await
}

运行服务器

现在要运行开发服务器,请调用以下命令:

systemfd --no-pid -s http::3000 -- cargo watch -x run
接下来: 数据库