Actix Web 安装与配置 #

前置要求 #

在安装 Actix Web 之前,你需要确保系统已安装以下工具:

工具 最低版本 说明
Rust 1.70+ Rust 编译器
Cargo 随 Rust 安装 包管理器
Git 任意版本 版本控制

安装 Rust #

Windows 安装 #

  1. 下载并运行 rustup-init.exe

  2. 按照提示完成安装:

text
1) Proceed with installation (default)
2) Customize installation
3) Cancel installation
> 1
  1. 验证安装:
powershell
rustc --version
cargo --version

macOS 安装 #

  1. 打开终端,运行安装脚本:
bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
  1. 配置环境变量:
bash
source $HOME/.cargo/env
  1. 验证安装:
bash
rustc --version
cargo --version

Linux 安装 #

  1. 运行安装脚本:
bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
  1. 配置环境变量:
bash
source $HOME/.cargo/env
  1. 验证安装:
bash
rustc --version
cargo --version

创建 Actix Web 项目 #

使用 Cargo 创建新项目 #

bash
cargo new my_actix_app
cd my_actix_app

添加依赖 #

编辑 Cargo.toml 文件:

toml
[package]
name = "my_actix_app"
version = "0.1.0"
edition = "2021"

[dependencies]
actix-web = "4"
actix-rt = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["full"] }

依赖说明 #

依赖 版本 说明
actix-web 4.x Actix Web 框架核心
actix-rt 2.x Actix 运行时
serde 1.x 序列化/反序列化
serde_json 1.x JSON 支持
tokio 1.x 异步运行时

项目结构 #

创建完成后,项目结构如下:

text
my_actix_app/
├── Cargo.toml          # 项目配置
├── Cargo.lock          # 依赖锁定
├── src/
│   └── main.rs         # 入口文件
└── target/             # 编译输出

最小示例 #

编辑 src/main.rs

rust
use actix_web::{web, App, HttpResponse, HttpServer, Responder};

async fn index() -> impl Responder {
    HttpResponse::Ok().body("Hello, Actix Web!")
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .route("/", web::get().to(index))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

运行项目 #

开发模式运行 #

bash
cargo run

输出:

text
Compiling my_actix_app v0.1.0
Finished dev [unoptimized + debuginfo] target(s)
Running `target/debug/my_actix_app`

访问服务 #

打开浏览器访问 http://127.0.0.1:8080/,你将看到:

text
Hello, Actix Web!

生产模式编译 #

bash
cargo build --release

编译后的二进制文件位于 target/release/my_actix_app

开发工具配置 #

VS Code 配置 #

推荐安装以下扩展:

  1. rust-analyzer:Rust 语言服务器
  2. CodeLLDB:调试支持
  3. Better TOML:TOML 文件支持
  4. crates:依赖版本提示

创建 .vscode/launch.json

json
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "lldb",
            "request": "launch",
            "name": "Debug Actix App",
            "cargo": {
                "args": ["build", "--bin=my_actix_app", "--package=my_actix_app"],
                "filter": {
                    "name": "my_actix_app",
                    "kind": "bin"
                }
            },
            "args": [],
            "cwd": "${workspaceFolder}"
        }
    ]
}

RustRover 配置 #

RustRover 是 JetBrains 的 Rust IDE:

  1. 打开 RustRover
  2. 选择 File > Open
  3. 选择项目目录
  4. 等待索引完成

自动重载开发 #

使用 cargo-watch 实现自动重载:

bash
cargo install cargo-watch
cargo watch -x run

环境变量配置 #

使用 .env 文件 #

添加 dotenvy 依赖:

toml
[dependencies]
dotenvy = "0.15"

src/main.rs 中加载:

rust
use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use std::env;

async fn index() -> impl Responder {
    let port = env::var("PORT").unwrap_or_else(|_| "8080".to_string());
    HttpResponse::Ok().body(format!("Running on port {}", port))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    dotenvy::dotenv().ok();
    
    let port = env::var("PORT")
        .unwrap_or_else(|_| "8080".to_string());
    
    HttpServer::new(|| {
        App::new()
            .route("/", web::get().to(index))
    })
    .bind(format!("127.0.0.1:{}", port))?
    .run()
    .await
}

创建 .env 文件:

text
PORT=3000
DATABASE_URL=postgres://user:pass@localhost/db

日志配置 #

添加日志依赖 #

toml
[dependencies]
env_logger = "0.10"
log = "0.4"

配置日志 #

rust
use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use log::info;

async fn index() -> impl Responder {
    info!("Index handler called");
    HttpResponse::Ok().body("Hello!")
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
    
    info!("Starting server at http://127.0.0.1:8080");
    
    HttpServer::new(|| {
        App::new()
            .route("/", web::get().to(index))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

运行时设置日志级别:

bash
RUST_LOG=debug cargo run

常见问题 #

1. 编译速度慢 #

解决方案:使用增量编译和优化

toml
# Cargo.toml
[profile.dev]
opt-level = 0
incremental = true

[profile.release]
opt-level = 3
lto = true

2. 端口被占用 #

错误信息:

text
Error: Os { code: 48, kind: AddrInUse, message: "Address already in use" }

解决方案:

bash
# 查找占用端口的进程
lsof -i :8080

# 终止进程
kill -9 <PID>

3. 依赖下载慢 #

配置国内镜像,创建 ~/.cargo/config

toml
[source.crates-io]
replace-with = 'ustc'

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

4. Windows 编译问题 #

安装 Visual Studio Build Tools:

  1. 下载 Visual Studio Build Tools
  2. 选择 “Desktop development with C++”
  3. 完成安装后重新编译

验证安装 #

运行以下命令验证安装是否成功:

bash
# 检查 Rust 版本
rustc --version

# 检查 Cargo 版本
cargo --version

# 创建测试项目
cargo new actix_test
cd actix_test

# 添加 actix-web 依赖
echo 'actix-web = "4"' >> Cargo.toml

# 编译项目
cargo build

如果以上命令都成功执行,说明环境配置完成!

下一步 #

环境搭建完成后,继续学习 第一个应用,创建你的第一个 Actix Web 应用!

最后更新:2026-03-29