Actix-Web入门

一、概述

Actix-Web 是 Rust 生态中性能最强大的 Web 框架之一,基于 Actor 模型和 Tokio 异步运行时。

Actix Web 在 TechEmpower 基准测试中 consistently 排名靠前,性能表现长期稳居全球前三,是构建高性能 Web 服务的理想选择。

核心优势

支持HTTP/1.x和HTTP/2
流媒体和流水线
具有可选宏的强大请求路由
完全兼容Tokio
保持活力,缓慢处理请求
客户端/服务器WebSockets支持
透明内容压缩/解压缩(br、gzip、deflate、zstd)
多部分流
静态资产
使用OpenSSL或Rustls的SSL支持
中间件(记录器、会话、CORS等)
与awc HTTP客户端集成
在稳定的Rust 1.72上运行+

 

github地址:https://github.com/actix/actix-web

官网:https://actix.rs/

image

二、快速开始

1. 新建工程

cargo new actix-hello
cd actix-hello

2. 在 Cargo.toml 中写入依赖

# Cargo.toml
[package]
name = "actix-web-demo"
version = "0.1.0"
edition = "2024"
 
[dependencies]
actix-web = "4"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1.0"

3. Hello World 示例

修改主代码 src/main.rs

use actix_web::{get, App, HttpResponse, HttpServer, Responder};
 
#[get("/")]
async fn hello() -> impl Responder {
    HttpResponse::Ok().body("Hello, world!")
}
 
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    println!("Starting HTTP server on http://127.0.0.1:8080");
    
    HttpServer::new(|| {
        App::new()
            .service(hello)
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

测试运行

cargo run

输出:

Starting HTTP server on http://127.0.0.1:8080

4. 测试网页

打开地址:http://127.0.0.1:8080

输出Hello, world!

 

三、Swagger UI

Swagger UI 是一个开源的工具,用于可视化和交互式地展示基于 OpenAPI 规范(以前称为 Swagger 规范)编写的 RESTful API 文档。

Actix-Web支持Swagger UI,下面基于Hello World来实现。

写入依赖

1. 修改Cargo.toml 中写入依赖

[package]
name = "actix_swagger"
version = "0.1.0"
edition = "2024"

[dependencies]
actix-web = "4"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1.0"
utoipa = { version = "5", features = ["actix_extras"] }
utoipa-swagger-ui = { version = "9", features = ["actix-web"] }
log = "0.4"      # 日志门面
env_logger = "0.11"     # 控制台实现

主代码 src/main.rs

2. 修改主代码 src/main.rs

use actix_web::{get, web, App, HttpServer, Responder};
use serde::Serialize;
use utoipa::{OpenApi, ToSchema};
use utoipa_swagger_ui::SwaggerUi;

/// 返回体
#[derive(Serialize, ToSchema)]
struct HelloReply {
    message: String,
}

/// 根路径接口
#[utoipa::path(
    responses(
        (status = 200, description = "Say hello", body = HelloReply)
    )
)]
#[get("/")]
async fn hello() -> impl Responder {
    web::Json(HelloReply {
        message: "Hello, world!".to_owned(),
    })
}

/// 合并 OpenAPI 文档
#[derive(OpenApi)]
#[openapi(
    paths(hello),
    components(schemas(HelloReply)),
    tags(
        (name = "hello", description = "Hello world endpoints")
    )
)]
struct ApiDoc;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    env_logger::init_from_env(env_logger::Env::default().default_filter_or("info"));
    log::info!("Starting HTTP server on http://127.0.0.1:8080");
    HttpServer::new(|| {
        App::new()
            .service(hello)                                     // 注册业务接口
            .service(                                           // 注册 Swagger UI
                SwaggerUi::new("/swagger-ui/{_:.*}")
                    .url("/api-doc/openapi.json", ApiDoc::openapi()),
            )
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

运行

测试运行

cargo run

输出:

[2025-11-26T05:52:19Z INFO  actix_swagger] Starting HTTP server on http://127.0.0.1:8080
[2025-11-26T05:52:19Z INFO  actix_server::builder] starting 32 workers
[2025-11-26T05:52:19Z INFO  actix_server::server] Actix runtime found; starting in Actix runtime
[2025-11-26T05:52:19Z INFO  actix_server::server] starting service: "actix-web-service-127.0.0.1:8080", workers: 32, listening on: 127.0.0.1:8080

验证

浏览器打开:

接口:http://localhost:8080/

image

 Swagger UI:http://localhost:8080/swagger-ui/

image

 即可看到自动生成的文档,并可直接在页面上点击 “Try it out” 调试 / 接口。

image

 

本文参考链接:https://blog.csdn.net/sinat_41617212/article/details/154069236

 
posted @ 2025-11-26 14:00  肖祥  阅读(7)  评论(0)    收藏  举报