Rust Web 全栈开发(三):使用 Actix 构建简单的 Web Service
Rust Web 全栈开发(三):使用 Actix 构建简单的 Web Service
- Rust Web 全栈开发(三):使用 Actix 构建简单的 Web Service
- 创建项目
- 配置依赖
- 编写路由并运行服务
- Actix 的基本组件
- Actix 的并发
- 尾声
Rust Web 全栈开发(三):使用 Actix 构建简单的 Web Service
参考视频:https://www.bilibili.com/video/BV1RP4y1G7KF
需要使用的 crate:
- actix-web
- actix-rt
本文介绍了如何使用 Actix 进行 Web 开发,包括新建项目、配置依赖、编写路由并运行服务。Actix 的基本组件包括 HTTP Server、Route 和 Handler,其并发机制支持异步 I/O 和多线程并行,确保高效处理请求。
创建项目
新建一个 Rust 项目,修改其 Cargo.toml:
[workspace]
然后在终端执行 cargo new webservice,在目录下创建一个 webservice 成员包。
在工作区内运行 cargo new 会自动将新创建的包添加到工作区内 Cargo.toml 的 [workspace] 定义中的 members 键中,如下所示:
此时,我们可以通过运行 cargo build 来构建工作区。项目目录下的文件应该是这样的:
├── Cargo.lock
├── Cargo.toml
├── webservice
│ ├── Cargo.toml
│ └── src
│ └── main.rs
└── target
配置依赖
webservice 需要引用 actix 相关库,打开 webservice/Cargo.toml,在 [dependencies] 部分添加:
actix-web = "4.2.1"
actix-rt = "2.7.0"
编写路由并运行服务
bin 是二进制可执行 crate,编译出的文件为二进制可执行文件。必须要有 main 函数作为入口。这种 crate 不需要在 Cargo.toml 中或 --crate-type 命令行参数中指定,会自动识别。
打开 webservice/Cargo.toml,添加一个 bin 的声明:
[[bin]]
name = "server1"
# path = "src/bin/server1.rs"
接着在 webservice/src 目录下创建一个 bin 目录,再在 bin 目录下创建 server1.rs,编写代码:
use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use std::io;// 配置 route
pub fn general_routes(cfg: &mut web::ServiceConfig) {cfg.route("/health", web::get().to(health_check_handler));
}// 配置 handler
pub async fn health_check_handler() -> impl Responder {HttpResponse::Ok().json("Actix Web Service is running!")
}// 实例化 HTTP server 并运行
#[actix_rt::main]
async fn main() -> io::Result<()> {// 构建 app,配置 routelet app = move || App::new().configure(general_routes);HttpServer::new(app).bind("localhost:3000")?.run().await
}
依旧是我们熟悉的 main -> route -> handler 的调用顺序。
在终端执行命令 cargo run -p webservice --bin server1,指定执行 webservice 库中的 server1。
或者 cd 到 webservice 目录,执行命令 cargo run --bin server1。
打开浏览器,访问 localhost:3000/health,可以看出程序运行成功:
Actix 的基本组件
Actix HTTP Server 实现了 HTTP 协议,默认情况下,它开启多个线程来处理来自互联网的请求。
接收到客户端的请求后,Actix HTTP Server 将其转发给 Actix App 内的对应路由,路由再将请求发给对应的 Handler 进行处理,处理完响应之后,将响应传回客户端。
Actix 的并发
Actix 支持两类并发:
- 异步 I/O:给定的 OS 原生线程在等待 I/O 时执行其他任务。
- 多线程并行:默认情况下启动 OS 原生线程的数量与系统逻辑 CPU 数量相同。
尾声
按 视频教程 的 Actix 相关库的版本
actix-web = "3"
actix-rt = "1.1.1"
会出现空指针解引用的错误,程序不能正常执行。
这里给出原版教程的官方源码地址:
https://github.com/peshwar9/rust-servers-services-apps/tree/master
后续如果还出现这种情况,建议对比源码看看。