Rust Web 框架选型:axum、actix-web 与 Rocket
MrSmy Lv5

Rust 写 Web 服务的框架选择比 Go 多,也更容易纠结。三个主流方案的定位差别很大:axum 是 tower 生态的一部分,actix-web 是性能标杆,Rocket 主打开发体验。这篇是拿同一个接口在三个框架上各写一遍的对比。

同一个接口,三种写法

需求:GET /users/{id} 返回用户信息,带数据库查询和错误处理。

axum

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
use axum::{
extract::{Path, State},
http::StatusCode,
response::{IntoResponse, Response},
routing::get,
Json, Router,
};

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))
}

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

actix-web

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
use actix_web::{get, web, App, HttpServer, Responder, HttpResponse};

#[get("/users/{id}")]
async fn get_user(
state: web::Data<AppState>,
id: web::Path<String>,
) -> actix_web::Result<impl Responder> {
let user = sqlx::query_as::<_, User>("SELECT id, name FROM users WHERE id = $1")
.bind(id.as_str())
.fetch_optional(&state.db)
.await?
.ok_or_else(|| actix_web::error::ErrorNotFound("用户不存在"))?;

Ok(web::Json(user))
}

HttpServer::new(move || {
App::new()
.app_data(web::Data::new(state.clone()))
.service(get_user)
})
.bind(("0.0.0.0", 8080))?
.run()
.await

Rocket

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#[macro_use] extern crate rocket;

#[get("/users/<id>")]
async fn get_user(state: &State<AppState>, id: String) -> Option<Json<User>> {
sqlx::query_as::<_, User>("SELECT id, name FROM users WHERE id = $1")
.bind(&id)
.fetch_optional(&state.db)
.await
.ok()
.flatten()
.map(Json)
}

#[launch]
fn rocket() -> _ {
rocket::build()
.manage(state)
.mount("/", routes![get_user])
}

差别一眼能看出来:

  • axum:提取器(extractor)是类型驱动的,错误用 Result<T, E> + IntoResponse
  • actix-web:属性宏 #[get] 定义路由,web::Data 做状态注入,错误用框架的 Error 类型
  • Rocket:宏最激进,#[launch] 就起服务,返回值 Option<Json<T>> 直接映射成 404/200

三者的定位

axum actix-web Rocket
出身 tokio 团队 actix actor 框架演化 早期社区项目
抽象基础 tower(Service) 自有抽象 自有抽象
生态整合 最好(tower-http 全能用) 好(有自己的中间件生态) 一般
学习曲线 中 中偏高 低
性能 高 极高 中高
成熟度 稳定(0.7/0.8) 4.x 稳定 0.5 稳定(RC 期很长)
编译速度 中 中 快

axum 最大的优势是 tower。整个 Rust 生态的中间件、限流、超时、追踪、压缩都是 tower 生态的,axum 不用自己做:

1
2
3
4
5
6
7
8
9
10
11
use tower::ServiceBuilder;
use tower_http::{trace::TraceLayer, compression::CompressionLayer, timeout::TimeoutLayer};

Router::new()
.route("/users/{id}", get(get_user))
.layer(
ServiceBuilder::new()
.layer(TraceLayer::new_for_http())
.layer(CompressionLayer::new())
.layer(TimeoutLayer::new(Duration::from_secs(15)))
)

而且这些中间件可以用在任何基于 tower 的东西上(包括 tonic gRPC),学到的东西是通用的。

actix-web 的优势是性能。它在各种 benchmark 上长期靠前,原因是:

  • 用了自己的 runtime 优化(虽然也基于 tokio)
  • 路由匹配是编译期生成的
  • 请求处理链高度优化

但要注意 benchmark 和真实业务差很远。我们测过同一个业务接口(查数据库 + 序列化 JSON),三者的 P99 差别在 5% 以内——瓶颈在数据库上。

Rocket 的优势是开发体验。它的宏让代码最短,配置也最友好(Rocket.toml):

1
2
3
4
5
6
7
8
9
[default]
port = 8080
log_level = "normal"

[release]
port = 80

[debug]
log_level = "debug"

代价是生态相对封闭,很多中间件要用 Rocket 自己的 fairing 机制写,不能复用 tower。

选型建议

我的结论很直接:新项目用 axum。

理由不是性能,是三点:

  1. tower 生态:中间件不用自己写,且学一次到处用
  2. tokio 官方关系:axum 是 tokio 组织维护的,和 runtime、hyper 的版本兼容性有保证
  3. 社区活跃度:遇到问题能搜到答案,库的适配也是优先支持 axum

actix-web 适合:

  • 已有 actix 项目(迁移成本高)
  • 极致追求吞吐量(比如做网关)
  • 团队习惯它的宏风格

Rocket 适合:

  • 内部小服务、原型验证
  • 团队刚学 Rust,想降低门槛
  • 不需要复杂中间件

一个容易忽略的问题:版本稳定性

axum 在 1.0 之前,minor 版本之间经常有 breaking change:

  • 0.6 → 0.7:Body 类型改了,Server 换成 axum::serve
  • 0.7 → 0.8:路径参数从 /:id 改成 /{id}

这意味着依赖升级需要谨慎。我们的做法是锁定 minor 版本,升级时专门排期。

actix-web 4.x 比较稳定,Rocket 0.5 之后也稳定了。这是选择时值得考虑的隐性成本——Rust 生态整体还年轻,版本稳定性不如 Go/Java。

共享状态与并发

三个框架都需要”跨请求共享状态”,机制不同:

1
2
3
4
5
6
7
8
9
10
11
12
// axum:要求 Clone,通常 Arc 包一层
#[derive(Clone)]
struct AppState {
db: PgPool, // PgPool 内部就是 Arc
cache: Arc<DashMap<String, String>>,
}

// actix-web:web::Data 内部是 Arc
let state = web::Data::new(AppState { db, cache });

// Rocket:manage 自动包 Arc
rocket::build().manage(AppState { db, cache })

axum 的 State<T> 要求 T: Clone + Send + Sync + 'static。用 Arc 包共享资源是最直接的方式。

一个坑:不要在 State 里放 Mutex<Connection> 然后每个请求锁它。连接池应该用 sqlx::PgPool 或 deadpool,锁连接会导致并发退化成串行。

错误处理的设计

axum 的做法最”Rust”——定义错误类型,实现 IntoResponse:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#[derive(thiserror::Error, Debug)]
enum AppError {
#[error("资源不存在")]
NotFound,
#[error("数据库错误")]
Database(#[from] sqlx::Error),
}

impl IntoResponse for AppError {
fn into_response(self) -> Response {
let status = match &self {
AppError::NotFound => StatusCode::NOT_FOUND,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
// 内部错误只记日志,不返回细节
if status.is_server_error() {
tracing::error!("{:?}", self);
}
(status, Json(json!({ "error": self.to_string() }))).into_response()
}
}

actix-web 也有 ResponseError trait,但它的错误模型和 actix_web::Error 更紧耦合,自定义类型要多写几层转换。

Rocket 的 Option<T> / Result<T, E> 最简洁,但错误信息不够可控——None 直接变 404,没有机会记录日志或者返回自定义格式。

实际迁移经验

我们从 actix-web 迁到了一个 axum 为主的架构,原因是想统一中间件层(同一个网关同时跑 HTTP 和 gRPC,都是 tower)。

迁移中的主要改动:

改动点 工作量
路由定义(宏 → Router::new().route()) 大,每个 handler 都要改
状态注入(web::Data → State) 中
提取器(web::Json → Json) 小,名字改改
中间件(fairing/中间件 → tower layer) 中,好处是能复用了
错误类型(actix_web::Error → 自定义 + IntoResponse) 中

整体花了两周(大约 40 个接口)。迁完之后中间件代码从 400 行减到 80 行——因为限流、超时、压缩、追踪都是现成的。

小结

Rust Web 框架的选择,我的建议是:

  1. 新项目:axum(生态判断,不是性能判断)
  2. 极致性能:actix-web,但先确认瓶颈真的在框架
  3. 快速原型 / 小工具:Rocket

更重要的一个判断是:Rust 写 Web 服务,框架只占 20% 的复杂度。真正花时间的是 sqlx 的类型检查、错误处理设计、Send 约束、以及编译等待。选哪个框架,对这些影响不大——所以与其纠结框架,不如先把项目结构和错误模型定下来。

  • 本文标题:Rust Web 框架选型:axum、actix-web 与 Rocket
  • 本文作者:MrSmy
  • 创建时间:2024-10-27 19:51:00
  • 本文链接:https://fengyang.live/2024/10/27/Rust Web框架选型:axum、actix-web与Rocket/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!