我是Actix的新手,我正在try 了解如何在一个线程上运行服务器并从另一个线程发送请求.
这就是我到目前为止掌握的代码
use actix_web::{web, App, HttpResponse, HttpServer};
use std::{sync::mpsc::channel, thread};
#[actix_web::main]
async fn main() {
let (tx, rx) = channel();
thread::spawn(move || {
let srv =
HttpServer::new(|| App::new().default_service(web::to(|| HttpResponse::NotFound())))
.bind("localhost:12347")
.unwrap()
.run();
let _ = tx.send(srv);
});
reqwest::get("http://localhost:12347").await.unwrap();
let srv = rx.recv().unwrap();
srv.handle().stop(false).await;
}
它编译得很好,但在发送请求时被卡住了.服务器好像在运行,所以我不明白为什么我没有收到响应.
编辑:按照@Finomennis和@afce25的建议,我将代码更改为使用任务而不是线程,并将结果await
修改为.run()
use actix_web::{web, App, HttpResponse, HttpServer};
use std::{sync::mpsc::channel, thread};
#[actix_web::main]
async fn main() {
let (tx, rx) = channel();
tokio::spawn(async move {
let srv =
HttpServer::new(|| App::new().default_service(web::to(|| HttpResponse::NotFound())))
.bind("localhost:12347")
.unwrap()
.run();
let _ = tx.send(srv.handle());
srv.await.unwrap();
});
reqwest::get("http://localhost:12347").await.unwrap();
let handle = rx.recv().unwrap();
handle.stop(false).await;
}
这就解决了问题.我仍然很好奇是否有可能在不同的线程上这样做,因为我不能在同步函数中使用await
.