自动重加载

在开发过程中,cargo自动重新编译变更代码会非常方便。这可以通过使用cargo-watch来完成 。由于actix应用程序通常会绑定到端口以侦听传入的HTTP请求,因此将它与listenfdsystemfd实用程序结合起来以确保套接字在应用程序编译和重新加载时保持打开状态是有意义的。

systemfd将打开一个套接字并将其传递给cargo-watch以监视更改,然后调用编译器并运行您的actix应用程序。actix应用程序将使用listenfd获取 systemfd打开的套接字systemfd。

需要的二进制文件

对于自动重新加载体验,您需要安装cargo-watchsystemfd。两者都用cargo install安装

  1. cargo install systemfd cargo-watch

修改代码

此外,您需要稍微修改您的actix应用程序,以便它可以获取由systemfd打开的外部套接字。将listenfd添加到您的应用依赖项中:

  1. [dependencices]
  2. listenfd = "0.3"

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

  1. extern crate listenfd;
  2. use listenfd::ListenFd;
  3. use actix_web::{server, App, HttpRequest, Responder};
  4. fn index(_req: HttpRequest) -> impl Responder {
  5. "Hello World!"
  6. }
  7. fn main() {
  8. let mut listenfd = ListenFd::from_env();
  9. let mut server = server::new(|| {
  10. App::new()
  11. .resource("/", |r| r.f(index))
  12. });
  13. server = if let Some(l) = listenfd.take_tcp_listener(0).unwrap() {
  14. server.listen(l)
  15. } else {
  16. server.bind("127.0.0.1:3000").unwrap()
  17. };
  18. server.run();
  19. }

运行服务器

现在运行开发服务器调用这个命令:

  1. systemfd --no-pid -s http::3000 -- cargo watch -x run