Rust Axum Web框架:從路由設計到中介軟體的5個生產級實戰模式
编程语言
Rust寫Web服務,為什麼總感覺在造輪子
你用Actix寫了兩年,社群風向突然變了;你試了Warp,發現那些Filter組合比業務邏輯還複雜;你剛想用Rocket,發現非同步支援還在nightly。2026年,Axum終於成為Rust Web框架的事實標準——Tokio團隊出品,Tower中介軟體生態,零成本抽象的效能,以及最關鍵的:學習曲線終於不像在攀巖了。
本文將從路由設計出發,帶你完成路由組織→Extractor提取→中介軟體→狀態管理→錯誤處理的5個生產級實戰模式,讓Axum從「能用」變成「好用」。
Axum核心概念
| 概念 | 說明 |
|---|---|
| Router | 路由器,將URL路徑對映到Handler函式 |
| Handler | 處理函式,接收Extractor引數,返回Response |
| Extractor | 提取器,從請求中提取資料(Path/Query/Json/State等) |
| Middleware | 中介軟體,透過Layer包裝Service實現橫切關注點 |
| State | 共享狀態,透過Arc包裝在Handler間共享 |
| Layer | Tower Layer,用於組合中介軟體 |
| Service | Tower Service,請求-回應處理單元 |
| Error | 錯誤處理,透過IntoResponse將錯誤轉為HTTP回應 |
請求處理流程
請求流程:
1. 客戶端傳送HTTP請求
2. Router匹配路徑,找到對應Handler
3. Extractor從請求中提取引數(Path/Query/Body/State)
4. Handler執行業務邏輯
5. Handler返回Response(或Error轉為Response)
6. 中介軟體Layer在請求前後執行(日誌/認證/限流等)
7. 回應返回客戶端
問題分析:Axum生產開發的5大挑戰
- 路由組織混亂:所有路由堆在一個
Router::new()裡,幾百個路由的檔案變成「麵條程式碼」 - Extractor型別爆炸:Handler引數超過4個就編譯報錯,複雜介面需要拆分或使用結構體
- 中介軟體順序陷阱:Layer的巢狀順序影響行為,認證在限流前還是後差別巨大
- 狀態管理困惑:Arc、Extension、State三種共享方式該用哪個,生命週期怎麼寫
- 錯誤處理不統一:每個Handler自己拼錯誤回應,前端拿到五花八門的錯誤格式
分步實操:5個生產級實戰模式
模式1:模組化路由組織
mod routes {
pub mod users;
pub mod products;
pub mod orders;
}
use axum::{Router, routing::{get, post, put, delete}, middleware, extract::State};
use std::sync::Arc;
pub struct AppState {
pub db: DbPool,
pub config: AppConfig,
}
pub type SharedState = Arc<AppState>;
pub fn create_router(state: SharedState) -> Router {
let api_routes = Router::new()
.nest("/users", routes::users::router())
.nest("/products", routes::products::router())
.nest("/orders", routes::orders::router())
.layer(middleware::from_fn(auth_middleware))
.layer(middleware::from_fn(logging_middleware));
Router::new()
.nest("/api/v1", api_routes)
.route("/health", get(health_check))
.with_state(state)
}
pub mod users {
use axum::{Router, routing::{get, post, put, delete}, extract::State};
use crate::{SharedState, routes::extractors::*};
pub fn router() -> Router<SharedState> {
Router::new()
.route("/", get(list_users).post(create_user))
.route("/{id}", get(get_user).put(update_user).delete(delete_user))
}
async fn list_users(
State(state): State<SharedState>,
Query(params): Query<ListUsersParams>,
) -> Result<Json<Vec<User>>, AppError> {
let users = state.db.fetch_users(params.offset, params.limit).await?;
Ok(Json(users))
}
async fn create_user(
State(state): State<SharedState>,
Json(payload): Json<CreateUserRequest>,
) -> Result<Json<User>, AppError> {
let user = state.db.create_user(payload).await?;
Ok(Json(user))
}
async fn get_user(
State(state): State<SharedState>,
Path(id): Path<Uuid>,
) -> Result<Json<User>, AppError> {
let user = state.db.get_user(id).await?;
Ok(Json(user))
}
async fn update_user(
State(state): State<SharedState>,
Path(id): Path<Uuid>,
Json(payload): Json<UpdateUserRequest>,
) -> Result<Json<User>, AppError> {
let user = state.db.update_user(id, payload).await?;
Ok(Json(user))
}
async fn delete_user(
State(state): State<SharedState>,
Path(id): Path<Uuid>,
) -> Result<StatusCode, AppError> {
state.db.delete_user(id).await?;
Ok(StatusCode::NO_CONTENT)
}
}
模式2:自定義Extractor解決引數爆炸
use axum::extract::{FromRequestParts, Query};
use axum::http::request::Parts;
use serde::Deserialize;
#[derive(Deserialize)]
pub struct PaginationParams {
pub offset: Option<u32>,
pub limit: Option<u32>,
}
#[derive(Deserialize)]
pub struct ListUsersParams {
pub offset: Option<u32>,
pub limit: Option<u32>,
pub role: Option<String>,
pub search: Option<String>,
}
pub struct PaginatedRequest<T> {
pub params: T,
pub offset: u32,
pub limit: u32,
}
#[axum::async_trait]
impl<T: serde::de::DeserializeOwned + Send + Sync> FromRequestParts<AppState> for PaginatedRequest<T> {
type Rejection = AppError;
async fn from_request_parts(parts: &mut Parts, state: &AppState) -> Result<Self, Self::Rejection> {
let Query(params): Query<T> = Query::from_request_parts(parts, state).await
.map_err(|e| AppError::BadRequest(e.body_text()))?;
let Query(pagination): Query<PaginationParams> = Query::from_request_parts(parts, state).await
.unwrap_or(Query(PaginationParams {
offset: Some(0),
limit: Some(20),
}));
Ok(PaginatedRequest {
params,
offset: pagination.offset.unwrap_or(0),
limit: pagination.limit.unwrap_or(20).min(100),
})
}
}
模式3:中介軟體組合與執行順序
use axum::{middleware, extract::Request, response::Response};
use axum::http::{HeaderValue, header};
use tower_http::cors::{CorsLayer, Any};
use tower_http::trace::TraceLayer;
use tower_http::limit::RateLimitLayer;
use tower::ServiceBuilder;
use std::time::Duration;
pub fn create_app_router(state: SharedState) -> Router {
let cors = CorsLayer::new()
.allow_origin(HeaderValue::from_static("https://example.com"))
.allow_methods(Any)
.allow_headers(Any);
Router::new()
.nest("/api/v1", api_routes())
.layer(
ServiceBuilder::new()
.layer(TraceLayer::new_for_http())
.layer(cors)
.layer(RateLimitLayer::new(100, Duration::from_secs(60)))
.layer(middleware::from_fn(request_id_middleware))
.layer(middleware::from_fn(auth_middleware))
.into_inner(),
)
.with_state(state)
}
async fn request_id_middleware(
mut request: Request,
next: middleware::Next,
) -> Response {
let request_id = uuid::Uuid::new_v4().to_string();
request.headers_mut().insert(
"x-request-id",
HeaderValue::from_str(&request_id).unwrap(),
);
let mut response = next.run(request).await;
response.headers_mut().insert(
"x-request-id",
HeaderValue::from_str(&request_id).unwrap(),
);
response
}
async fn auth_middleware(
request: Request,
next: middleware::Next,
) -> Result<Response, AppError> {
let auth_header = request.headers()
.get("authorization")
.and_then(|v| v.to_str().ok())
.ok_or(AppError::Unauthorized)?;
if !auth_header.starts_with("Bearer ") {
return Err(AppError::Unauthorized);
}
let token = &auth_header[7..];
validate_token(token)?;
Ok(next.run(request).await)
}
模式4:型別安全的狀態管理
use std::sync::Arc;
use tokio::sync::RwLock;
pub struct AppState {
pub db: DbPool,
pub redis: RedisClient,
pub config: AppConfig,
pub cache: Arc<RwLock<lru::LruCache<String, Vec<u8>>>>,
}
impl AppState {
pub fn new(db: DbPool, redis: RedisClient, config: AppConfig) -> Self {
Self {
db,
redis,
config,
cache: Arc::new(RwLock::new(
lru::LruCache::new(NonZeroUsize::new(10000).unwrap())
)),
}
}
}
pub type SharedState = Arc<AppState>;
async fn handler_with_cache(
State(state): State<SharedState>,
Path(key): Path<String>,
) -> Result<Response, AppError> {
{
let cache = state.cache.read().await;
if let Some(value) = cache.get(&key) {
return Ok((*value.clone()).into_response());
}
}
let value = state.db.fetch_by_key(&key).await?;
{
let mut cache = state.cache.write().await;
cache.put(key.clone(), value.clone());
}
Ok(value.into_response())
}
模式5:統一錯誤處理
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::Json;
use serde::Serialize;
#[derive(Debug)]
pub enum AppError {
BadRequest(String),
Unauthorized,
Forbidden(String),
NotFound(String),
Conflict(String),
InternalServerError(String),
DatabaseError(sqlx::Error),
}
#[derive(Serialize)]
struct ErrorResponse {
error: ErrorDetail,
}
#[derive(Serialize)]
struct ErrorDetail {
code: u16,
message: String,
#[serde(skip_serializing_if = "Option::is_none")]
details: Option<Vec<FieldError>>,
}
#[derive(Serialize)]
struct FieldError {
field: String,
message: String,
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, message) = match &self {
AppError::BadRequest(msg) => (StatusCode::BAD_REQUEST, msg.clone()),
AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "Unauthorized".to_string()),
AppError::Forbidden(msg) => (StatusCode::FORBIDDEN, msg.clone()),
AppError::NotFound(msg) => (StatusCode::NOT_FOUND, msg.clone()),
AppError::Conflict(msg) => (StatusCode::CONFLICT, msg.clone()),
AppError::InternalServerError(msg) => {
tracing::error!("Internal error: {}", msg);
(StatusCode::INTERNAL_SERVER_ERROR, "Internal server error".to_string())
}
AppError::DatabaseError(e) => {
tracing::error!("Database error: {:?}", e);
(StatusCode::INTERNAL_SERVER_ERROR, "Internal server error".to_string())
}
};
let body = ErrorResponse {
error: ErrorDetail {
code: status.as_u16(),
message,
details: None,
},
};
(status, Json(body)).into_response()
}
}
impl From<sqlx::Error> for AppError {
fn from(e: sqlx::Error) -> Self {
match e {
sqlx::Error::RowNotFound => AppError::NotFound("Resource not found".to_string()),
sqlx::Error::Database(db_err) => {
if db_err.code().map(|c| c == "23505").unwrap_or(false) {
AppError::Conflict("Duplicate entry".to_string())
} else {
AppError::DatabaseError(sqlx::Error::Database(db_err))
}
}
other => AppError::DatabaseError(other),
}
}
}
避坑指南
坑1:Handler引數超過4個
// ❌ 錯誤:Handler最多支援4個Extractor引數
async fn handler(
Path(id): Path<Uuid>, // 1
Query(params): Query<Params>, // 2
State(state): State<SharedState>, // 3
Json(body): Json<RequestBody>, // 4
Extension(ctx): Extension<RequestContext>, // 5! 編譯報錯
) { ... }
// ✅ 正確:用結構體合併引數
#[derive(Deserialize)]
struct CreateUserRequest {
name: String,
email: String,
role: Option<String>,
}
async fn handler(
Path(id): Path<Uuid>,
State(state): State<SharedState>,
Json(body): Json<CreateUserRequest>,
) { ... }
坑2:State型別不匹配
// ❌ 錯誤:Router和Handler的State型別不一致
let app = Router::new()
.route("/users", get(handler))
.with_state(Arc::new(AppState { ... }));
async fn handler(State(state): State<Arc<OtherState>>) { ... }
// 編譯錯誤:型別不匹配
// ✅ 正確:統一使用type alias
type SharedState = Arc<AppState>;
let app = Router::new()
.route("/users", get(handler))
.with_state(Arc::new(AppState { ... }));
async fn handler(State(state): State<SharedState>) { ... }
坑3:中介軟體順序錯誤
// ❌ 錯誤:認證在限流之後,未認證請求也消耗限流配額
.layer(middleware::from_fn(rate_limit))
.layer(middleware::from_fn(auth))
// ✅ 正確:先認證再限流,只對已認證請求限流
.layer(middleware::from_fn(auth))
.layer(middleware::from_fn(rate_limit))
坑4:在中介軟體中修改請求體後忘記更新Content-Length
// ❌ 錯誤:修改body後Content-Length不匹配
async fn body_transform(req: Request, next: Next) -> Response {
let (parts, body) = req.into_parts();
let bytes = axum::body::to_bytes(body, 1024 * 1024).await.unwrap();
let modified = transform(bytes);
next.run(Request::from_parts(parts, Body::from(modified))).await
}
// ✅ 正確:重建請求時讓框架自動處理Content-Length
async fn body_transform(req: Request, next: Next) -> Response {
let (mut parts, body) = req.into_parts();
let bytes = axum::body::to_bytes(body, 1024 * 1024).await.unwrap();
let modified = transform(bytes);
parts.headers.remove("content-length");
next.run(Request::from_parts(parts, Body::from(modified))).await
}
坑5:RwLock死鎖
// ❌ 錯誤:read guard跨await導致死鎖
async fn handler(State(state): State<SharedState>) {
let cache = state.cache.read().await;
let result = fetch_from_db().await; // .await with lock held!
cache.get(&key);
}
// ✅ 正確:在await前釋放鎖
async fn handler(State(state): State<SharedState>) {
let value = {
let cache = state.cache.read().await;
cache.get(&key).cloned()
}; // lock released here
let result = fetch_from_db().await;
}
報錯排查
| 序號 | 報錯訊息 | 原因 | 解決方法 |
|---|---|---|---|
| 1 | handler has too many arguments |
Handler引數超過4個Extractor | 用結構體合併引數或自定義Extractor |
| 2 | mismatched types: expected X, found Y |
State型別不匹配 | 統一使用type alias,確保Router和Handler一致 |
| 3 | the trait FromRequest is not implemented |
型別未實現Extractor | 實現FromRequestParts或使用已有Extractor |
| 4 | cannot borrow as mutable |
不可變引用下嘗試修改 | 使用RwLock或Arc包裝可變狀態 |
| 5 | future cannot be sent between threads safely |
非Send型別跨await | 確保跨await的資料實現Send trait |
| 6 | request was dropped before response |
中介軟體未正確呼叫next.run() | 確保中介軟體始終呼叫next並返回Response |
| 7 | missing state in router |
路由未呼叫with_state | 在Router上呼叫.with_state(state) |
| 8 | route not found |
路由路徑不匹配 | 檢查路徑引數格式,Axum用{id}不是:id |
| 9 | payload too large |
請求體超過預設限制 | 使用DefaultBodyLimit::max()調整限制 |
| 10 | connection pool timed out |
資料庫連線池耗盡 | 增大pool size或新增連線超時配置 |
進階最佳化
1. Tower Service組合實現請求管道
use tower::ServiceBuilder;
use tower_http::compression::CompressionLayer;
use tower_http::cors::CorsLayer;
use tower_http::limit::RequestBodyLimitLayer;
use tower_http::timeout::TimeoutLayer;
use tower_http::trace::TraceLayer;
use std::time::Duration;
pub fn production_layers() -> tower::ServiceBuilder<
tower::layer::layer_fn::LayerFn<...>,
> {
ServiceBuilder::new()
.layer(TraceLayer::new_for_http())
.layer(TimeoutLayer::new(Duration::from_secs(30)))
.layer(CompressionLayer::new())
.layer(RequestBodyLimitLayer::new(10 * 1024 * 1024))
.layer(CorsLayer::permissive())
}
2. 優雅關閉與連線排空
use axum::Router;
use tokio::signal;
use tokio::net::TcpListener;
pub async fn run_server(app: Router, addr: &str) -> Result<(), Box<dyn std::error::Error>> {
let listener = TcpListener::bind(addr).await?;
tracing::info!("Server listening on {}", addr);
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal())
.await?;
tracing::info!("Server shutdown complete");
Ok(())
}
async fn shutdown_signal() {
let ctrl_c = async {
signal::ctrl_c()
.await
.expect("failed to install Ctrl+C handler");
};
#[cfg(unix)]
let terminate = async {
signal::unix::signal(signal::unix::SignalKind::terminate())
.expect("failed to install signal handler")
.recv()
.await;
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! {
_ = ctrl_c => { tracing::info!("Received Ctrl+C"); },
_ = terminate => { tracing::info!("Received SIGTERM"); },
}
}
3. 請求級別的上下文傳播
use axum::extract::Request;
use axum::middleware::Next;
use axum::response::Response;
#[derive(Clone)]
pub struct RequestContext {
pub request_id: String,
pub user_id: Option<Uuid>,
pub trace_id: Option<String>,
}
async fn context_middleware(
request: Request,
next: Next,
) -> Response {
let request_id = request.headers()
.get("x-request-id")
.and_then(|v| v.to_str().ok())
.unwrap_or("unknown")
.to_string();
let ctx = RequestContext {
request_id,
user_id: None,
trace_id: None,
};
let mut response = next.run(request).await;
response.headers_mut().insert(
"x-request-id",
HeaderValue::from_str(&ctx.request_id).unwrap(),
);
response
}
對比分析
| 維度 | Axum | Actix Web | Warp | Rocket | Gin (Go) |
|---|---|---|---|---|---|
| 非同步執行時 | Tokio | Tokio | Tokio | 自帶 | Goroutine |
| 中介軟體生態 | ✅Tower全生態 | ⚠️自建 | ⚠️Filter組合 | ⚠️Fairing | ✅豐富 |
| 學習曲線 | ⭐中 | ⭐陡 | ⭐極陡 | ⭐平緩 | ⭐平緩 |
| 效能 | ⭐極高 | ⭐極高 | ⭐極高 | ⭐高 | ⭐高 |
| 型別安全 | ✅編譯時 | ⚠️部分 | ✅編譯時 | ✅ | ❌執行時 |
| 巨集依賴 | 少 | 多 | 無 | 多 | 少 |
| 社群活躍度 | ⭐極高 | ⭐高 | ⭐中 | ⭐中 | ⭐極高 |
| 文件品質 | ⭐好 | ⭐好 | ⭐中 | ⭐極好 | ⭐好 |
總結:Axum的核心優勢不是效能(Rust Web框架效能都很強),而是組合性——基於Tower的中介軟體生態讓你像搭積木一樣組裝請求處理管道。2026年的生產實踐:用模組化Router組織路由→自定義Extractor簡化Handler→ServiceBuilder組合中介軟體→統一AppError處理→Arc共享狀態。關鍵是要理解Tower的Service/Layer模型,這是Axum的根基,也是它區別於其他框架的靈魂。
線上工具推薦
- JSON格式化:/zh-TW/json/format
- Base64編解碼:/zh-TW/encode/base64
- Hash計算:/zh-TW/encode/hash
- JWT解碼:/zh-TW/encode/jwt-decode
本站提供瀏覽器本地工具,免註冊即可試用 →
#Rust#Axum#Web框架#中间件#异步HTTP#2026#Tower