在我的 actix-web 处理程序中,我想调用一个在后台运行并立即向用户返回响应的函数:
async fn heavy_computation() -> {
// do some long running computation
}
async fn index(req: HttpRequest) -> impl Responder {
// start computation
heavy_computation();
// render and return template
let out context = Context::new();
context.insert("foo", "bar");
render_template("my_template.html", &context)
// computation finishes
}
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(web::resource("/").route(web::get().to(index)))
})
.bind("127.0.0.1:8080")?
.run()
.await
}
如果我使用await
来等待未来结果,那么响应直到计算完成后才会返回;如果我不使用await
,函数根本不会执行。
Actor
并使用do_send方法。https://docs.rs/actix/0.10.0-alpha.3/actix/struct.Addr.html#method.do_send 如果这是你想要的答案,我可以为你写一篇。 - Njuguna Mureithi