Actix-web 框架
问题
actix-web 的核心特点是什么?
答案
actix-web 是 Rust 最成熟的 Web 框架之一,以高性能著称。
基础示例
use actix_web::{web, App, HttpServer, HttpResponse, Responder};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct User {
name: String,
age: u32,
}
// Handler 函数
async fn hello() -> impl Responder {
HttpResponse::Ok().body("Hello, World!")
}
async fn create_user(user: web::Json<User>) -> impl Responder {
HttpResponse::Created().json(user.into_inner())
}
async fn get_user(path: web::Path<u64>) -> impl Responder {
let id = path.into_inner();
HttpResponse::Ok().json(User {
name: format!("User {}", id),
age: 25,
})
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.route("/", web::get().to(hello))
.service(
web::scope("/api")
.route("/users", web::post().to(create_user))
.route("/users/{id}", web::get().to(get_user))
)
})
.bind("127.0.0.1:8080")?
.run()
.await
}
axum vs actix-web
| 维度 | axum | actix-web |
|---|---|---|
| 运行时 | tokio | 自有(兼容 tokio) |
| 中间件 | Tower Layer | 自有 Middleware trait |
| 提取器 | FromRequest | FromRequest |
| 状态 | State<T> | web::Data<T> |
| 路由 | Router | App + scope |
| WebSocket | axum 内置 | actix-ws |
| 生态兼容 | tower-http | actix 生态 |
常见面试问题
Q1: 如何在 axum 和 actix-web 之间选择?
答案:
- 选 axum:新项目、需要与 tonic/tower 生态集成、喜欢简洁 API
- 选 actix-web:已有 actix 项目、团队熟悉、需要极致性能(两者性能差距极小)
两者性能在 TechEmpower 基准测试中都名列前茅,选择更多取决于生态偏好。