在不同端口上运行多个actix应用程序

9

我正在尝试运行两个应用程序(一个在3006端口上进行管理,另一个在8080端口上提供数据)。


它们共享数据库池、缓存等。

对于 actix 1.0,我已经实现了这一点(我不知道这是否是最好的方法):

let server = Server::build()
  // FIRST APP
  .bind("", "0.0.0.0:3006", move || {
      HttpService::build().finish({
          App::new()
              .wrap(actix_Logger::new(
                  "WMTS %a %r %s %b %{Referer}i %{User-Agent}i %T",
              ))
              .data(pool.clone())
              .data(cache.clone())
              .service(
                  web::scope("/utils")
                      .route(
                          "one",
                          web::get().to(api::one),
                      )
                      .route("two", web::get().to(api::two))
              )
              .service(
                  web::scope("/data")
                      .route("get_data", web::get().to(api::get_data)),
              )
      })
  })
  .unwrap()
  // SECOND APP
  .bind("", "0.0.0.0:8080", move || {
      HttpService::build().finish(
          App::new()
              .wrap(actix_Logger::new(
                  "API %a %r %s %b %{Referer}i %{User-Agent}i %T",
              ))
              .data(pool.clone())
              .data(cache.clone())
              .service(web::resource("/graphql").route(web::post().to(api::graphql)))
              .service(web::resource("/health").route(web::get().to(api::health)))
              .service(web::resource("/metrics").route(web::get().to(api::metrics))),
      )
  })
  .unwrap();

  server.run()?;

但怎么才能在actix 2.0中使其工作呢?
1个回答

13

actix-web 的 API 而言,从 1.02.0,实际上没有太多变化。这是件好事,因为您仍然可以使用熟悉的 API 来配置路由、应用程序数据、日志记录器等。

有一个变化,即 actix-web 已经转换到了 async / await。您的应用程序也需要适应这种变化。

//# actix-rt = "1.0"
//# actix-web = "2.0"
//# futures = "0.3"
use actix_web::{web, App, HttpServer, Responder};
use futures::future;

async fn utils_one() -> impl Responder {
    "Utils one reached\n"
}

async fn health() -> impl Responder {
    "All good\n"
}

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    let s1 = HttpServer::new(move || {
            App::new().service(web::scope("/utils").route("/one", web::get().to(utils_one)))
        })
        .bind("0.0.0.0:3006")?
        .run();
    let s2 = HttpServer::new(move || {
            App::new().service(web::resource("/health").route(web::get().to(health)))
        })
        .bind("0.0.0.0:8080")?
        .run();
    future::try_join(s1, s2).await?;

    Ok(())
}

我想你仍然可以使用Server::build API来构建多个绑定,但这里展示的方法更加模块化。HttpServer::run现在仅返回一个Future。你可以将两者连接起来,然后等待它们的完成。

它会像预期的那样工作:

$ curl http://127.0.0.1:3006/utils/one
Utils one reached
$ curl http://127.0.0.1:8080/health
All good

太棒了!谢谢!我还不熟悉新的异步等待发布。 - Etienne Prothon
你知道如何更改HttpServer future的错误类型吗?我想将其映射到 anyhow::Error,因为我还需要与另一个不返回 std::io::Error 的 future 进行合并。 - Etienne Prothon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接