rust - 返回响应后,在后台运行长时间运行的异步函数

标签 rust async-await rust-actix actix-web

在我的一个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编码,则根本不会执行该功能。

最佳答案

假设您使用tokio作为异步运行时,则可以使用tokio::task::spawn生成两个任务,然后将它们与tokio::join结合在一起:

use tokio::task;
use tokio::time;
use std::time::Duration;

async fn heavy_computation() {
    time::delay_for(Duration::from_millis(2000)).await;
    println!("heavy computation finished");
}

async fn light_computation() {
    time::delay_for(Duration::from_millis(500)).await;
    println!("light computation finished");
}

#[tokio::main]
async fn main() {
    let heavy = task::spawn(heavy_computation());
    println!("computation started");
    let light = task::spawn(async move {
        for _ in 0..3 {
            light_computation().await;
        }
    });
    let (a, b) = tokio::join!(heavy, light);
    // use the results so the compiler doesn't complain
    a.unwrap();
    b.unwrap();
}
Link to playground

关于rust - 返回响应后,在后台运行长时间运行的异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62982737/

相关文章:

rust - 无法从 `i32` 构建类型为 `std::iter::Iterator<Item=_>` 的集合

javascript - 是否需要将函数声明为异步函数才能返回 promise ?

rust - 从另一个未定义 T 的 actor 处理程序调用 MyActor::from_registry() 时如何确定类型注释?

rust - 如何使用actix在函数内部使用数据库池?

rust - Actix-Web 2.0 JsonConfig error_handler无法正常工作

multithreading - 如何将对堆栈变量的引用传递给线程?

rust - 静态可变数据的惯用替代方法是什么?

rust - 如何基于CENNZnet创建一个新的区 block 链项目?

c# - 为什么 File.ReadAllLinesAsync() 会阻塞 UI 线程?

c# - 不等待 SaveChangesAsync() 是否安全?