tokio::spawn makes axum won't take request in parallel #1695
-
// src/server.rs
use axum::{
extract::Path,
response::{IntoResponse, Response},
routing::get,
};
pub struct Server {}
impl Server {
pub async fn run() -> Result<(), Box<dyn std::error::Error>> {
let axum_http_make_service = axum::Router::new()
.route("/:sec", get(wait_sec_event))
.into_make_service();
let http_server =
axum::Server::bind(&"0.0.0.0:4000".parse().unwrap()).serve(axum_http_make_service);
let http_handle = tokio::spawn(http_server);
let _ = tokio::try_join!(http_handle)?;
Ok(())
}
}
async fn wait_sec_event(Path(sec): Path<String>) -> Response {
let a = std::time::Duration::from_secs(sec.parse::<u64>().unwrap());
std::thread::sleep(a);
"yo".into_response()
} // src/app.rs
use std::net::SocketAddr;
use crate::server;
pub struct App {
port: SocketAddr,
}
impl App {
pub fn new(p: SocketAddr) -> Self {
Self { port: p }
}
pub async fn run(self) -> Result<(), Box<dyn std::error::Error>> {
server::Server::run().await
}
} // src/main.rs
use std::net::SocketAddr;
use app::App;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// build our application with a single route
let app = App::new(SocketAddr::from(([0, 0, 0, 0], 4000)));
app.run().await
}
pub mod app;
pub mod server; When I tried to implement a axum server means if I do curl 127.0.0.1:4000/10 then curl 127.0.0.1:4000/3 , the later request won't execute until the first one is finished |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
I just figure this out. I shoudn't use |
Beta Was this translation helpful? Give feedback.
-
wait, I'm confused. Why does passing it into a tokio::spawn change std::thread::sleep to be blocking? I was able to reproduce that std::thread::sleep() is non-blocking when using .await.unwrap() but it is blocking when using tokio::spawn() to wrap the Server future. |
Beta Was this translation helpful? Give feedback.
I just figure this out. I shoudn't use
std::thread::sleep()
within the async function