axumで重い処理を tokio::spawn で別スレッドにしてページのレンダリングを先にした場合、ユーザが別ページに飛んだ場合でも、別スレッドの関数は止まらない。
async fn handle_index() -> axum::response::Html<String> {
let handle = tokio::spawn(async move {
let _ = delay().await;
});
println!("main thread");
let tera = tera::Tera::new("templates/*").unwrap();
let mut context = tera::Context::new();
context.insert("title", "Index page");
let output = tera.render("app.html", &context);
return axum::response::Html(output.unwrap());
}
async fn delay() {
thread::sleep(Duration::from_secs(10));
println!("sub thread");
}
async fn handle_sub() -> axum::response::Html<String> {
let tera = tera::Tera::new("templates/*").unwrap();
let data = 100;
let mut context = tera::Context::new();
context.insert("title", "Index page");
let output = tera.render("app.html", &context);
return axum::response::Html(output.unwrap());
}
Finished `dev` profile [unoptimized + debuginfo] target(s) in 9.57s
Running `target/debug/axum`
main thread
sub thread
そりゃそうだと思っていても、実際にテストしないと安心できませんね。