跳转至

Actix Rust Web

一句话概述:Actix Web 是 Rust 语言最流行的 Web 框架,性能登顶 TechEmpower 基准测试,类型安全、零成本抽象、内存安全,适合构建高性能、高可靠的后端服务。

核心知识点

概念白话解释
App应用 = Actix Web 的核心实例
Handler处理器 = 异步函数处理请求
Extractor提取器 = 从请求中自动提取数据(路径、查询、JSON)
Middleware中间件 = 请求/响应的通用处理
State状态 = 在多个处理器间共享的数据(如数据库连接池)
HttpServerHTTP 服务器 = 多线程异步服务器

安装配置

cargo new myapp && cd myapp  # 创建 Rust 项目
# Cargo.toml
[dependencies]
actix-web = "4"       # Actix Web 框架
actix-rt = "2"        # 异步运行时
serde = { version = "1", features = ["derive"] }  # 序列化/反序列化
serde_json = "1"      # JSON 处理

基本使用

// main.rs
use actix_web::{web, App, HttpServer, HttpResponse, middleware};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]  // 支持 JSON 序列化
struct Sample {
    id: u32,
    name: String,
    species: String,
}

#[derive(Deserialize)]
struct CreateSample {
    name: String,
    species: String,
}

// GET /api/samples
async fn list_samples() -> HttpResponse {
    let samples = vec![Sample { id: 1, name: "S001".into(), species: "human".into() }];
    HttpResponse::Ok().json(samples)  // 返回 JSON
}

// POST /api/samples
async fn create_sample(body: web::Json<CreateSample>) -> HttpResponse {
    let sample = Sample {
        id: 1,
        name: body.name.clone(),  // 从请求体获取
        species: body.species.clone(),
    };
    HttpResponse::Created().json(sample)  // 201 返回
}

// GET /api/samples/{id}
async fn get_sample(path: web::Path<u32>) -> HttpResponse {
    let id = path.into_inner();  // 路径参数
    HttpResponse::Ok().json(Sample { id, name: format!("S{:03}", id), species: "human".into() })
}

#[actix_web::main]  // 异步 main 函数
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .wrap(middleware::Logger::default())  // 日志中间件
            .service(
                web::scope("/api")  // 路由组前缀
                    .route("/samples", web::get().to(list_samples))
                    .route("/samples", web::post().to(create_sample))
                    .route("/samples/{id}", web::get().to(get_sample))
            )
    })
    .bind("127.0.0.1:8080")?  // 绑定地址
    .run()
    .await
}

共享状态(数据库连接)

use std::sync::Mutex;

struct AppState {
    db: Mutex<Vec<Sample>>,  // 线程安全的共享状态
}

async fn list(data: web::Data<AppState>) -> HttpResponse {
    let db = data.db.lock().unwrap();
    HttpResponse::Ok().json(&*db)
}

// main 中注册
App::new().app_data(web::Data::new(AppState { db: Mutex::new(vec![]) }))

常见报错

报错信息原因解决方法
Json deserialize errorJSON 格式不对检查请求体字段和类型
IO error: Address already in use端口被占换端口
Mutex poisoned锁中发生 panic使用错误恢复或换 RwLock

速查表

// === 提取器 ===
web::Path<T>          // 路径参数
web::Query<T>         // 查询参数
web::Json<T>          // JSON 请求体
web::Data<T>          // 共享状态
web::Form<T>          // 表单数据

// === 响应 ===
HttpResponse::Ok().json(data)       // 200 + JSON
HttpResponse::Created().json(data)  // 201
HttpResponse::NotFound().finish()   // 404
HttpResponse::BadRequest().body("error")  // 400

// === 路由 ===
web::get().to(handler)   // GET
web::post().to(handler)  // POST
web::scope("/api")       // 路由组

// === 构建运行 ===
cargo run                // 开发运行
cargo build --release    // 生产构建

参考:Actix Web 文档 | 更新于 2026 年