Rust 异步 Web 服务:Tokio 与 axum 实战
MrSmy Lv5

Go 的 goroutine 是”写起来像同步”的并发,Rust 的 async 是”零成本的 Future”。两者目标相似,心智模型差别不小。这篇用 axum 写一个能上线的 API 服务,记录从 Go 迁过来的思维转变点。

Rust 2024 edition 在 1.85 稳定,所以这次直接用了新 edition。

从 runtime 开始

Rust 标准库只有 Future 定义,没有执行器。必须选一个 runtime:

1
2
3
4
5
6
7
8
[dependencies]
tokio = { version = "1", features = ["full"] }
axum = "0.8"
serde = { version = "1", features = ["derive"] }
tower = "0.5"
tower-http = { version = "0.6", features = ["trace", "cors", "compression-gzip"] }
anyhow = "1"
thiserror = "2"
1
2
3
4
#[tokio::main]
async fn main() {
// ...
}

#[tokio::main] 展开后是 tokio::runtime::Builder::new_multi_thread().enable_all().block_on(...)。等价于显式写:

1
2
3
4
5
6
7
8
fn main() {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(4)
.enable_all()
.build()
.unwrap();
rt.block_on(async_main());
}

需要精细控制(线程数、线程名、栈大小)时用显式版本。

最小可用的服务

1
2
3
4
5
6
7
8
9
10
11
12
13
use axum::{routing::get, Router};

async fn health() -> &'static str {
"ok"
}

#[tokio::main]
async fn main() {
let app = Router::new().route("/health", get(health));

let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await.unwrap();
axum::serve(listener, app).await.unwrap();
}

注意 axum 0.8 的一个 breaking change:**路径参数语法从 /:id 改成 /{id}**。

1
2
3
4
5
// axum 0.7
Router::new().route("/users/:id", get(get_user))

// axum 0.8
Router::new().route("/users/{id}", get(get_user))

原因是新版用了 matchit 0.8,换成了更明确的定界符。老代码升级时会直接 panic(路由解析失败),很好定位。

Handler 与提取器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
use axum::{
extract::{Path, Query, State},
Json,
};
use serde::{Deserialize, Serialize};

#[derive(Deserialize)]
struct ListQuery {
page: Option<u32>,
size: Option<u32>,
}

#[derive(Serialize)]
struct User {
id: String,
name: String,
}

async fn list_users(Query(q): Query<ListQuery>) -> Json<Vec<User>> {
let page = q.page.unwrap_or(1);
let size = q.size.unwrap_or(20).min(100); // 上限保护
// ...
Json(vec![])
}

async fn get_user(Path(id): Path<String>) -> Json<User> {
Json(User { id, name: "mrsmy".into() })
}

提取器的顺序很重要:body 提取器(Json<T>、Form<T>)必须放最后,因为它消费请求体,放在前面会导致后面的提取器拿不到。

需要拿原始 Request 时,用 Request<Body>,但要放在所有其他提取器之前。

共享状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
use std::sync::Arc;

#[derive(Clone)]
struct AppState {
db: sqlx::PgPool,
cache: Arc<Cache>,
}

async fn get_user(
State(state): State<AppState>,
Path(id): Path<String>,
) -> Result<Json<User>, AppError> {
let user = sqlx::query_as::<_, User>("SELECT id, name FROM users WHERE id = $1")
.bind(&id)
.fetch_optional(&state.db)
.await?
.ok_or(AppError::NotFound)?;

Ok(Json(user))
}

fn main() {
let state = AppState { db, cache };
let app = Router::new()
.route("/users/{id}", get(get_user))
.with_state(state);
}

State<T> 要求 T: Clone,所以内部用 Arc 包共享资源。Arc<Cache> 里的 Cache 需要内部可变性时,用 tokio::sync::RwLock 或 dashmap:

1
2
3
4
5
use dashmap::DashMap;

struct Cache {
map: DashMap<String, String>, // 并发安全的 HashMap
}

DashMap 是分片锁,比 RwLock<HashMap> 在并发写时好很多。

错误处理:Go 的对比

Go 里习惯写 if err != nil { return err },Rust 里 ? 就够。但 HTTP 层需要把错误转成响应:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
use axum::{http::StatusCode, response::{IntoResponse, Response}, Json};

#[derive(thiserror::Error, Debug)]
enum AppError {
#[error("资源不存在")]
NotFound,

#[error("参数错误: {0}")]
BadRequest(String),

#[error("数据库错误")]
Database(#[from] sqlx::Error),

#[error("内部错误")]
Internal(#[from] anyhow::Error),
}

impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, msg) = match &self {
AppError::NotFound => (StatusCode::NOT_FOUND, self.to_string()),
AppError::BadRequest(m) => (StatusCode::BAD_REQUEST, m.clone()),
AppError::Database(e) => {
tracing::error!("db error: {:?}", e); // 内部细节只进日志
(StatusCode::INTERNAL_SERVER_ERROR, "服务内部错误".into())
}
AppError::Internal(e) => {
tracing::error!("internal: {:?}", e);
(StatusCode::INTERNAL_SERVER_ERROR, "服务内部错误".into())
}
};

(status, Json(serde_json::json!({ "error": msg }))).into_response()
}
}

这样 Handler 里可以直接写 ?:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
async fn create_user(
State(state): State<AppState>,
Json(req): Json<CreateUserReq>,
) -> Result<Json<User>, AppError> {
if req.name.is_empty() {
return Err(AppError::BadRequest("名字不能为空".into()));
}

let user = sqlx::query_as::<_, User>("INSERT INTO users (name) VALUES ($1) RETURNING id, name")
.bind(&req.name)
.fetch_one(&state.db)
.await?; // #[from] 自动转成 AppError::Database

Ok(Json(user))
}

? + From 的组合,效果等价于 Go 的 if err != nil,但代码量少一半,且不会漏判。

中间件

axum 基于 tower 的 Service 抽象,中间件就是”包一层”:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
use tower_http::trace::TraceLayer;
use tower_http::cors::CorsLayer;
use tower::ServiceBuilder;
use std::time::Duration;

let app = Router::new()
.route("/users/{id}", get(get_user))
.layer(
ServiceBuilder::new()
.layer(TraceLayer::new_for_http())
.layer(CorsLayer::permissive())
.timeout(Duration::from_secs(15))
.concurrency_limit(500)
)
.with_state(state);

tower-http 提供了大部分常用中间件:超时、限流、压缩、CORS、请求 ID。这是 axum 相比其他 Rust Web 框架的优势——复用 tower 生态。

自己写中间件用 from_fn:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
use axum::{extract::Request, middleware::Next, response::Response};

async fn request_id(mut req: Request, next: Next) -> Response {
let id = req
.headers()
.get("x-request-id")
.and_then(|v| v.to_str().ok())
.map(String::from)
.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());

req.extensions_mut().insert(RequestId(id.clone()));

let mut resp = next.run(req).await;
resp.headers_mut().insert("x-request-id", id.parse().unwrap());
resp
}

// 使用
Router::new().layer(axum::middleware::from_fn(request_id))

和 Go 的 c.Next() 是一样的”环绕”思路,只是表达方式不同。

优雅关闭

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
use tokio::signal;

async fn shutdown_signal() {
let ctrl_c = async {
signal::ctrl_c().await.expect("安装 Ctrl+C 处理器失败");
};

#[cfg(unix)]
let terminate = async {
signal::unix::signal(signal::unix::SignalKind::terminate())
.expect("安装 SIGTERM 处理器失败")
.recv()
.await;
};

#[cfg(not(unix))]
let terminate = std::future::pending::<()>();

tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
}

tracing::info!("开始关闭");
}

axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal())
.await
.unwrap();

with_graceful_shutdown 会等正在处理的请求完成。比 Go 的 srv.Shutdown(ctx) 更简洁——不需要自己设超时,因为 tower 有 timeout 中间件兜着。

踩过的坑

1. Send 约束

1
2
3
4
5
6
// 编译错误:future cannot be sent between threads safely
async fn handler() -> String {
let guard = MUTEX.lock().unwrap(); // std::sync::MutexGuard 不是 Send
tokio::time::sleep(Duration::from_secs(1)).await;
guard.to_string()
}

跨 .await 持有 std::sync::Mutex 的 guard 会导致 Future 不是 Send,axum 的 handler 要求 Send。

修法:要么缩小作用域(在 await 前 drop(guard)),要么用 tokio::sync::Mutex(它的 guard 是 Send)。

这个错误信息不太直观,但原因很清楚:任何跨 await 持有的非 Send 类型都会传播到整个 Future。

2. 忘了 .await

1
sqlx::query("...").execute(&pool);      // 没 await → 什么都没发生

编译器会警告 unused_must_use,但不会报错。行为是”接口静默成功但数据没写进去”。开 #![deny(unused_must_use)] 能拦住。

3. 递归 async 需要 Box

1
2
3
4
5
6
7
8
9
10
11
// 错误:递归 async fn 大小无法确定
async fn walk(dir: PathBuf) {
walk(dir.join("sub")).await;
}

// 正确
fn walk(dir: PathBuf) -> Pin<Box<dyn Future<Output = ()> + Send>> {
Box::pin(async move {
walk(dir.join("sub")).await;
})
}

async fn 的返回类型是匿名 Future,递归时大小无法确定,必须装箱。

4. spawn 需要 'static

1
2
3
4
5
6
7
8
9
let data = vec![1, 2, 3];
tokio::spawn(async {
println!("{:?}", data); // 错误:借用不是 'static
});

// 正确:move 进去
tokio::spawn(async move {
println!("{:?}", data);
});

spawn 出来的任务生命周期不受调用方约束,所以只能持有 'static 数据。这和 Go 里 go func(){ ... }() 捕获变量的行为不同——Go 会自动让变量逃逸到堆,Rust 要求你显式 move。

5. block_on 里再 block_on

1
2
3
4
5
#[tokio::main]
async fn main() {
// 错误:不能嵌套 runtime
tokio::runtime::Runtime::new().unwrap().block_on(async {});
}

在 async 上下文里调用阻塞的 runtime 会 panic。需要在 async 里跑阻塞代码,用 tokio::task::spawn_blocking。

与 Go 的心智对照

概念 Go Rust
并发单元 goroutine tokio::spawn 的 Future
共享状态 sync.Mutex Arc<Mutex<T>> / Arc<RwLock<T>>
错误传播 if err != nil ? + From
取消 context.Context 直接 drop future(隐式取消)
超时 context.WithTimeout tower 的 TimeoutLayer
优雅关闭 srv.Shutdown(ctx) with_graceful_shutdown

最本质的区别在”取消”:Go 需要显式传 context 并在每个阻塞点检查;Rust 的 Future 是惰性的,drop 掉就取消,不需要传参。代价是”取消点”变成了隐式的——你不知道在哪个 .await 被取消了。

这带来一个实践差异:Go 里写”必须完成的操作”要注意用 context.WithoutCancel;Rust 里要注意”drop 可能发生在任意 await 点”,需要保证原子性的操作要包在 spawn 里(spawn 出的任务不会被外部 drop 影响)。

小结

axum + tokio 的组合写起来比想象中顺手:? 的错误处理比 Go 的 if err 简洁,tower 中间件是现成的,with_graceful_shutdown 一行搞定。主要成本在三处:Send 约束、'static 约束、以及编译时间(中等项目首次全量编译 1-2 分钟,增量几秒)。

如果团队是 Go 背景,转到 Rust 最需要调整的不是语法,而是”提前想清楚数据的生命周期和所有权”这个习惯——它让编译期报错变多,但也让运行时问题变少。

  • 本文标题:Rust 异步 Web 服务:Tokio 与 axum 实战
  • 本文作者:MrSmy
  • 创建时间:2025-05-18 20:14:00
  • 本文链接:https://fengyang.live/2025/05/18/Rust异步Web服务:Tokio与axum实战/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!