【Rust开发知识】Actix-web 开发环境搭建完整教程

Actix-web 开发环境搭建完整教程

  • [Actix-web 开发环境搭建完整教程](#Actix-web 开发环境搭建完整教程)
    • [一、前置准备:安装 Rust 工具链](#一、前置准备:安装 Rust 工具链)
      • [1. 安装 Rustup(Rust 版本管理器)](#1. 安装 Rustup(Rust 版本管理器))
      • [2. 验证安装](#2. 验证安装)
      • [3. 配置国内镜像源(加速依赖下载)](#3. 配置国内镜像源(加速依赖下载))
      • [4. 安装开发工具](#4. 安装开发工具)
    • [二、创建 Actix-web 项目](#二、创建 Actix-web 项目)
      • [1. 创建项目骨架](#1. 创建项目骨架)
      • [2. 添加 Actix-web 依赖](#2. 添加 Actix-web 依赖)
    • [三、编写第一个 Actix-web 应用](#三、编写第一个 Actix-web 应用)
      • [1. 基础代码(`src/main.rs`)](#1. 基础代码(src/main.rs))
      • [2. 配置环境变量(可选)](#2. 配置环境变量(可选))
    • 四、运行与测试服务
      • [1. 启动开发服务器](#1. 启动开发服务器)
      • [2. 测试端点](#2. 测试端点)
      • [3. 热重载开发(提高效率)](#3. 热重载开发(提高效率))
    • 五、高级配置(实战必备)
      • [1. 添加中间件(日志、压缩、跨域)](#1. 添加中间件(日志、压缩、跨域))
      • [2. 数据库连接(PostgreSQL + SQLx)](#2. 数据库连接(PostgreSQL + SQLx))
        • [步骤 1:添加依赖(`Cargo.toml`)](#步骤 1:添加依赖(Cargo.toml))
        • [步骤 2:创建数据库连接池(`src/db.rs`)](#步骤 2:创建数据库连接池(src/db.rs))
        • [步骤 3:在 `main.rs` 中集成数据库](#步骤 3:在 main.rs 中集成数据库)
      • [3. HTTPS 配置(生产环境必备)](#3. HTTPS 配置(生产环境必备))
        • [步骤 1:添加依赖](#步骤 1:添加依赖)
        • [步骤 2:加载证书并启动 HTTPS 服务器](#步骤 2:加载证书并启动 HTTPS 服务器)
    • 六、开发工具与调试
    • [七、Docker 部署](#七、Docker 部署)
      • [1. 编写 Dockerfile(多阶段构建)](#1. 编写 Dockerfile(多阶段构建))
      • [2. 构建并运行容器](#2. 构建并运行容器)
    • 八、常见问题解决
      • [1. 端口占用](#1. 端口占用)
      • [2. 依赖冲突](#2. 依赖冲突)
      • [3. 性能调优](#3. 性能调优)
    • 九、学习资源推荐
    • 总结
    • 相关文档

Actix-web 开发环境搭建完整教程

本教程将从零开始,手把手教你搭建 Actix-web 开发环境,涵盖 Rust 安装、项目创建、依赖配置、代码编写、运行调试、测试部署 全流程,适合 Rust 新手和有经验的开发者。

一、前置准备:安装 Rust 工具链

Actix-web 基于 Rust 语言,需先安装 Rust 工具链(含编译器 rustc、包管理器 cargo、构建工具等)。

1. 安装 Rustup(Rust 版本管理器)

打开终端,执行以下命令(根据系统选择):

bash 复制代码
# Linux/macOS
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

# Windows
# 下载 rustup-init.exe 从 https://rustup.rs/,双击运行并按提示安装

安装过程中选择 默认配置(直接按 Enter),安装完成后重启终端。

2. 验证安装

执行以下命令,输出版本号即成功:

bash 复制代码
rustc --version  # 示例:rustc 1.74.1 (a28077b28 2023-12-04)
cargo --version   # 示例:cargo 1.74.1 (ecb9851af 2023-10-18)

3. 配置国内镜像源(加速依赖下载)

国内用户建议配置清华/中科大镜像,编辑 ~/.cargo/config 文件(Windows 路径:C:\Users\<用户名>\.cargo\config):

toml 复制代码
[source.crates-io]
registry = "https://github.com/rust-lang/crates.io-index"
replace-with = 'tuna'  # 使用清华镜像

[source.tuna]
registry = "https://mirrors.tuna.tsinghua.edu.cn/git/crates.io-index.git"

[net]
git-fetch-with-cli = true  # 使用系统 git 下载(避免 SSL 问题)

4. 安装开发工具

安装 Rust 官方推荐的代码格式化、语法检查和 VS Code 扩展:

bash 复制代码
# 安装 rustfmt(代码格式化)和 clippy(静态检查)
rustup component add rustfmt clippy

# 安装 VS Code 扩展(如果用 VS Code)
code --install-extension rust-lang.rust-analyzer  # Rust 语言服务器
code --install-extension serayuzgur.crates         # 依赖管理
code --install-extension bungcip.better-toml      # TOML 文件支持

二、创建 Actix-web 项目

1. 创建项目骨架

使用 cargo new 创建二进制项目(可执行程序):

bash 复制代码
cargo new actix-demo --bin  # --bin 表示创建可执行项目(默认)
cd actix-demo               # 进入项目目录

项目结构如下:

复制代码
actix-demo/
├── Cargo.toml   # 项目依赖和配置
└── src/
    └── main.rs   # 程序入口

2. 添加 Actix-web 依赖

编辑 Cargo.toml,添加 Actix-web 及相关依赖:

toml 复制代码
[package]
name = "actix-demo"
version = "0.1.0"
edition = "2021"  # Rust 2021 版本

[dependencies]
actix-web = "4.4"          # Actix-web 核心库(最新稳定版 4.4.x)
actix-rt = "2.9"           # Actix 异步运行时(必须依赖)
env_logger = "0.10"        # 环境变量日志配置
log = "0.4"                # 日志门面(统一日志接口)
serde = { version = "1.0", features = ["derive"] }  # JSON 序列化/反序列化
dotenv = "0.15"            # 加载 .env 环境变量文件
chrono = { version = "0.4", features = ["serde"] }  # 时间处理(可选,示例中用)

版本说明:actix-web = "4.4" 表示兼容 4.4.x 系列最新版,可通过 https://crates.io/crates/actix-web 查看最新版本。

三、编写第一个 Actix-web 应用

1. 基础代码(src/main.rs

实现一个包含 健康检查、首页、JSON API 的简单服务:

rust 复制代码
use actix_web::{
    get,          // 路由宏:GET 请求
    App,          // 应用构建器
    HttpResponse, // 响应类型
    HttpServer,   // HTTP 服务器
    Responder,    // 响应 trait
    web,          // 工具模块(数据提取、JSON 等)
};
use chrono::Utc;  // 时间处理(需添加 chrono 依赖)
use dotenv::dotenv;
use log::info;
use serde::Serialize;
use std::env;

// 1. 健康检查端点(GET /health)
#[get("/health")]
async fn health_check() -> impl Responder {
    HttpResponse::Ok().body("OK")  // 返回 200 OK + 文本 "OK"
}

// 2. 首页端点(GET /)
#[get("/")]
async fn index() -> impl Responder {
    HttpResponse::Ok().body("Welcome to Actix-web! 🚀")
}

// 3. JSON API 端点(GET /api/time)
#[derive(Serialize)]  // 自动实现 JSON 序列化
struct TimeResponse {
    timestamp: i64,    // 时间戳(秒)
    datetime: String,  // 格式化时间
}
#[get("/api/time")]
async fn get_current_time() -> impl Responder {
    let now = Utc::now();
    HttpResponse::Ok().json(TimeResponse {
        timestamp: now.timestamp(),
        datetime: now.format("%Y-%m-%d %H:%M:%S").to_string(),
    })
}

#[actix_web::main]  // Actix 异步运行时入口(等价于 #[tokio::main])
async fn main() -> std::io::Result<()> {
    // 加载 .env 文件(若存在)
    dotenv().ok();
    // 初始化日志(从环境变量 RUST_LOG 读取级别,默认 info)
    env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));

    // 从环境变量读取端口(默认 8080)
    let port = env::var("PORT").unwrap_or_else(|_| "8080".to_string());
    let bind_addr = format!("0.0.0.0:{}", port);  // 绑定所有网卡

    info!("Starting Actix-web server at http://{}", bind_addr);

    // 启动 HTTP 服务器
    HttpServer::new(|| {
        App::new()  // 创建应用实例
            .service(health_check)  // 注册健康检查路由
            .service(index)         // 注册首页路由
            .service(get_current_time)  // 注册 JSON API 路由
    })
    .bind(bind_addr)?  // 绑定地址(失败返回错误)
    .run()             // 运行服务器
    .await             // 等待异步完成
}

2. 配置环境变量(可选)

创建 .env 文件(项目根目录),自定义端口和日志级别:

env 复制代码
# .env 文件
PORT=8080                  # 服务端口(默认 8080)
RUST_LOG=actix_web=debug   # 日志级别:debug(显示详细请求日志)

四、运行与测试服务

1. 启动开发服务器

在项目根目录执行:

bash 复制代码
cargo run

首次运行会下载依赖(需几分钟,国内镜像加速后更快),成功后输出:

复制代码
[INFO  actix_demo] Starting Actix-web server at http://0.0.0.0:8080

2. 测试端点

打开新终端,用 curl 或浏览器测试:

bash 复制代码
# 1. 首页
curl http://localhost:8080/
# 输出:Welcome to Actix-web! 🚀

# 2. 健康检查
curl http://localhost:8080/health
# 输出:OK

# 3. JSON API(返回当前时间和时间戳)
curl http://localhost:8080/api/time
# 输出:{"timestamp":1717234567,"datetime":"2024-06-01 12:36:07"}

3. 热重载开发(提高效率)

安装 cargo-watch 实现代码修改后自动重启:

bash 复制代码
cargo install cargo-watch  # 安装
cargo watch -x run          # 启动热重载(修改代码后自动重启服务)

五、高级配置(实战必备)

1. 添加中间件(日志、压缩、跨域)

Actix-web 中间件用于处理通用逻辑(如日志、认证、CORS),示例添加 日志中间件响应压缩中间件

rust 复制代码
use actix_web::middleware::{Compress, Logger};  // 导入中间件

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // ...(省略前面的初始化代码)

    HttpServer::new(|| {
        App::new()
            .wrap(Logger::default())  // 日志中间件(记录请求方法、路径、状态码)
            .wrap(Compress::default()) // 响应压缩(自动 gzip/deflate)
            .service(health_check)
            .service(index)
            .service(get_current_time)
    })
    .bind(bind_addr)?
    .run()
    .await
}

2. 数据库连接(PostgreSQL + SQLx)

实际项目需连接数据库,以 PostgreSQL + SQLx 为例:

步骤 1:添加依赖(Cargo.toml
toml 复制代码
[dependencies]
# ... 其他依赖
sqlx = { version = "0.7", features = ["runtime-tokio-native-tls", "postgres", "macros"] }  # SQLx 核心
tokio = { version = "1", features = ["full"] }  # Tokio 运行时(Actix 依赖)
步骤 2:创建数据库连接池(src/db.rs
rust 复制代码
use sqlx::postgres::PgPoolOptions;
use std::time::Duration;

/// 数据库连接池类型别名
pub type DbPool = sqlx::Pool<sqlx::Postgres>;

/// 创建数据库连接池
pub async fn create_pool(database_url: &str) -> Result<DbPool, sqlx::Error> {
    PgPoolOptions::new()
        .max_connections(5)  // 最大连接数
        .acquire_timeout(Duration::from_secs(3))  // 连接超时
        .connect(database_url)
        .await
}
步骤 3:在 main.rs 中集成数据库
rust 复制代码
mod db;  // 导入 db 模块

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // ...(省略初始化日志)

    // 从环境变量读取数据库 URL(示例:postgres://user:pass@localhost/dbname)
    let database_url = env::var("DATABASE_URL")
        .expect("DATABASE_URL environment variable not set");
    let pool = db::create_pool(&database_url).await.expect("Failed to create DB pool");

    HttpServer::new(move || {
        App::new()
            .app_data(web::Data::new(pool.clone()))  // 共享数据库连接池
            .service(your_db_handler)  // 注册需要数据库的路由
            // ... 其他服务
    })
    // ... 绑定地址并运行
}

3. HTTPS 配置(生产环境必备)

使用 rustls 配置 HTTPS(需提前准备 SSL 证书):

步骤 1:添加依赖
toml 复制代码
[dependencies]
# ... 其他依赖
rustls = "0.21"          # TLS 实现
rustls-pemfile = "1.0"   # PEM 证书解析
步骤 2:加载证书并启动 HTTPS 服务器
rust 复制代码
use rustls::ServerConfig;
use rustls_pemfile::{certs, pkcs8_private_keys};
use std::fs::File;
use std::io::BufReader;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // ...(省略初始化代码)

    // 加载 SSL 证书和私钥(示例路径:./cert.pem, ./key.pem)
    let cert_file = &mut BufReader::new(File::open("cert.pem").unwrap());
    let key_file = &mut BufReader::new(File::open("key.pem").unwrap());
    let cert_chain = certs(cert_file).unwrap().into_iter().map(rustls::Certificate).collect();
    let mut keys = pkcs8_private_keys(key_file).unwrap();
    let key = rustls::PrivateKey(keys.remove(0));

    // 配置 TLS
    let tls_config = ServerConfig::builder()
        .with_safe_defaults()
        .with_no_client_auth()
        .with_single_cert(cert_chain, key)
        .unwrap();

    // 启动 HTTPS 服务器(绑定 443 端口)
    HttpServer::new(|| App::new().service(index))
        .bind_rustls("0.0.0.0:443", tls_config)?
        .run()
        .await
}

六、开发工具与调试

1. VS Code 调试配置

创建 .vscode/launch.json,配置调试入口:

json 复制代码
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "lldb",
            "request": "launch",
            "name": "Debug Actix-web",
            "program": "${workspaceFolder}/target/debug/actix-demo",
            "args": [],
            "cwd": "${workspaceFolder}",
            "preLaunchTask": "cargo build"  // 调试前自动构建
        }
    ]
}

创建 .vscode/tasks.json,配置构建任务:

json 复制代码
{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "cargo build",
            "type": "shell",
            "command": "cargo",
            "args": ["build"],
            "problemMatcher": ["$rustc"]
        }
    ]
}

2. 单元测试与集成测试

Actix-web 提供 actix_web::test 模块,方便编写测试:

单元测试示例(tests/health_check.rs
rust 复制代码
use actix_web::{test, web, App, http::StatusCode};
use actix_demo::{health_check, index};  // 导入处理函数

#[actix_web::test]  // 标记为 Actix 测试
async fn test_health_check() {
    // 初始化测试服务
    let app = test::init_service(
        App::new().service(health_check)
    ).await;

    // 发送 GET 请求到 /health
    let req = test::TestRequest::get().uri("/health").to_request();
    let resp = test::call_service(&app, req).await;

    // 断言:状态码 200,响应体为 "OK"
    assert_eq!(resp.status(), StatusCode::OK);
    let body = test::read_body(resp).await;
    assert_eq!(body, "OK");
}

运行测试:

bash 复制代码
cargo test  # 运行所有测试
cargo test test_health_check  # 运行指定测试

七、Docker 部署

1. 编写 Dockerfile(多阶段构建)

dockerfile 复制代码
# 阶段 1:构建依赖和项目
FROM rust:1.74 as builder
WORKDIR /app
COPY . .
RUN apt-get update && apt-get install -y cmake pkg-config libssl-dev  # 安装系统依赖
RUN cargo build --release  # 编译 Release 版本

# 阶段 2:运行环境(轻量 Debian 镜像)
FROM debian:bullseye-slim
RUN apt-get update && apt-get install -y libssl-dev ca-certificates && rm -rf /var/lib/apt/lists/*
COPY --from=builder /app/target/release/actix-demo /usr/local/bin/
EXPOSE 8080  # 暴露端口
CMD ["actix-demo"]  # 启动命令

2. 构建并运行容器

bash 复制代码
docker build -t actix-demo .  # 构建镜像
docker run -d -p 8080:8080 --name actix-app actix-demo  # 后台运行容器

八、常见问题解决

1. 端口占用

bash 复制代码
# Linux/macOS:查找占用 8080 端口的进程
lsof -i :8080
kill -9 <PID>  # 终止进程

# Windows:查找占用端口
netstat -ano | findstr :8080
taskkill /F /PID <PID>

2. 依赖冲突

bash 复制代码
cargo clean          # 清除 target 目录(解决缓存问题)
cargo update         # 更新依赖到兼容版本
cargo tree           # 查看依赖树(排查冲突)

3. 性能调优

  • 调整线程池HttpServer::workers(n) 设置工作线程数(建议设为 CPU 核心数 × 2)
  • 启用 HTTP/2.bind_h2c("0.0.0.0:8080") 或 HTTPS 自动支持
  • 静态文件缓存 :用 actix-files 中间件处理静态资源,设置 Cache-Control

九、学习资源推荐

  1. 官方文档

  2. 实战教程

  3. 示例项目

总结

通过以上步骤,你已完成 Actix-web 开发环境的搭建,并实现了一个包含路由、中间件、日志的基础服务。接下来可深入学习:

  • 数据库集成(Diesel/SQLx)
  • 身份验证(JWT/OAuth2)
  • WebSocket 实时通信
  • 部署到云服务(AWS/GCP)

相关文档

【知识科普】.toml配置文件说明
【Rust编程知识】在 Windows 下搭建完整的 Rust 开发环境
【开发语言】Rust语言介绍

相关推荐
程序猿_极客5 小时前
【2025 年最新版】Java JDK 安装与环境配置教程(附图文超详细,Windows+macOS 通用)
java·开发语言·windows·macos·jdk
二哈喇子!8 小时前
BOM模型
开发语言·前端·javascript·bom
二哈喇子!8 小时前
Vue2 监听器 watcher
前端·javascript·vue.js
二哈喇子!8 小时前
空指针异常
开发语言
咚为8 小时前
Rust Print 终极指南:从底层原理到全场景实战
开发语言·后端·rust
%xiao Q8 小时前
GESP C++五级-202406
android·开发语言·c++
Psycho_MrZhang8 小时前
Neo4j Python SDK手册
开发语言·python·neo4j
yanyu-yaya8 小时前
前端面试题
前端·面试·前端框架
Traced back8 小时前
# C# + SQL Server 实现自动清理功能的完整方案:按数量与按日期双模式
开发语言·c#
sin22018 小时前
MyBatis的执行流程
java·开发语言·mybatis