第一章:Rust 异步编程与 Axum 框架入门
博客v1.0系列教程(Rust)博客 v1.0 系列教程 (Rust)
1.1 Rust 异步编程基础
Rust 的异步编程模型基于零开销抽象设计,没有垃圾回收器,没有运行时开销。核心概念包括 Future、async/await 和运行时。
Future trait
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
pub trait Future {
type Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}
async/await
use tokio::time::{sleep, Duration};
async fn fetch_data() -> Result<String, std::io::Error> {
// 模拟异步 I/O 操作
sleep(Duration::from_millis(100)).await;
Ok("data".to_string())
}
#[tokio::main]
async fn main() {
let result = fetch_data().await;
println!("{}", result);
}
Tokio 运行时
Tokio 是 Rust 最流行的异步运行时,提供:
- 多线程工作窃取调度器
- 高效的 I/O 驱动(epoll / IOCP / kqueue)
- 计时器、同步原语、网络模块
1.2 Axum 框架核心概念
Axum 是 Tokio 生态中的 HTTP 框架,基于 tower 中间件栈设计。
路由与处理器
use axum::{
routing::get,
Router,
};
async fn hello() -> &'static str {
"Hello, World!"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(hello))
.route("/health", get(|| async { "OK" }));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
1.3 提取器
Axum 的提取器从 HTTP 请求中提取数据:
use axum::{
extract::{Path, Query, Json, State},
http::Uri,
};
// 路径参数
async fn get_article(Path(id): Path<i64>) -> Json<Article> {
// ...
}
// 查询参数
#[derive(Deserialize)]
struct Pagination {
page: Option<u64>,
page_size: Option<u64>,
}
async fn list_articles(Query(params): Query<Pagination>) -> Json<Vec<Article>> {
// ...
}
// 请求体
async fn create_article(Json(body): Json<CreateArticleDto>) -> Json<Article> {
// ...
}
// 共享状态
#[derive(Clone)]
struct AppState {
pool: PgPool,
}
async fn with_state(State(state): State<AppState>) -> String {
// 使用 state.pool
}
1.4 项目初始化
# 创建项目
cargo new rabitlogic-blog
cd rabitlogic-blog
# 添加依赖
cargo add axum tokio serde serde_json sqlx --features tokio/postgres,runtime-tokio
cargo add tower-http --features cors
cargo add tracing tracing-subscriber
Cargo.toml
[package]
name = "rabitlogic-blog"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.7"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.8", features = ["runtime-tokio", "postgres"] }
tower-http = { version = "0.5", features = ["cors"] }
tracing = "0.1"
tracing-subscriber = "0.3"
1.5 Dioxus SSR 集成
Dioxus 0.7 支持 SSR 渲染:
use dioxus::prelude::*;
#[component]
fn App() -> Element {
rsx! { h1 { "Hello, Dioxus SSR!" } }
}
fn render_ssr() -> String {
let mut dom = VirtualDom::new(App);
dom.rebuild_in_place();
dioxus_ssr::render(&dom)
}
下一章将深入模块化项目结构设计。
rustaxumasynctokio