Rust 异步编程高级应用指南
1. 异步编程基础
Rust 的异步编程模型基于 Future trait 和 async/await 语法,它允许我们编写非阻塞的代码,提高程序的性能和响应速度。
use tokio::time::{sleep, Duration};
async fn hello() {
println!("Hello");
sleep(Duration::from_secs(1)).await;
println!("World");
}
#[tokio::main]
async fn main() {
hello().await;
}
2. Future 和 Task
2.1 Future
Future 是 Rust 异步编程的核心概念,它表示一个可能尚未完成的计算。
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::time::{sleep, Duration};
struct MyFuture {
delay: Pin<Box<dyn Future<Output = ()>>>,
}
impl Future for MyFuture {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.delay.as_mut().poll(cx)
}
}
async fn my_async_function() {
println!("Before delay");
let future = MyFuture {
delay: Box::pin(sleep(Duration::from_secs(1))),
};
future.await;
println!("After delay");
}
#[tokio::main]
async fn main() {
my_async_function().await;
}
2.2 Task
Task 是 Future 的执行单元,它由异步运行时管理。
use tokio::spawn;
use tokio::time::{sleep, Duration};
async fn task1() {
println!("Task 1 started");
sleep(Duration::from_secs(1)).await;
println!("Task 1 finished");
}
async fn task2() {
println!("Task 2 started");
sleep(Duration::from_secs(0.5)).await;
println!("Task 2 finished");
}
#[tokio::main]
async fn main() {
let handle1 = spawn(task1());
let handle2 = spawn(task2());
handle1.await.unwrap();
handle2.await.unwrap();
}
3. 高级异步编程技巧
3.1 并行执行多个任务
use tokio::join;
use tokio::time::{sleep, Duration};
async fn task1() -> u32 {
sleep(Duration::from_secs(1)).await;
1
}
async fn task2() -> u32 {
sleep(Duration::from_secs(0.5)).await;
2
}
async fn task3() -> u32 {
sleep(Duration::from_secs(1.5)).await;
3
}
#[tokio::main]
async fn main() {
let (result1, result2, result3) = join!(task1(), task2(), task3());
println!("Results: {}, {}, {}", result1, result2, result3);
}
3.2 超时处理
use tokio::time::{timeout, Duration};
use tokio::time::error::Elapsed;
async fn slow_operation() {
tokio::time::sleep(Duration::from_secs(2)).await;
println!("Slow operation finished");
}
#[tokio::main]
async fn main() {
match timeout(Duration::from_secs(1), slow_operation()).await {
Ok(_) => println!("Operation completed successfully"),
Err(Elapsed(_)) => println!("Operation timed out"),
}
}
3.3 任务取消
use tokio::spawn;
use tokio::time::{sleep, Duration};
use tokio::sync::oneshot;
async fn long_running_task(mut shutdown: oneshot::Receiver<()>) {
println!("Starting long running task");
for i in 0..10 {
println!("Working... {}", i);
// 检查是否收到取消信号
tokio::select! {
_ = sleep(Duration::from_millis(500)) => {},
_ = &mut shutdown => {
println!("Task was cancelled");
return;
}
}
}
println!("Task finished");
}
#[tokio::main]
async fn main() {
let (tx, rx) = oneshot::channel();
let handle = spawn(long_running_task(rx));
// 等待一段时间后取消任务
sleep(Duration::from_secs(2)).await;
tx.send(()).unwrap();
handle.await.unwrap();
println!("Main finished");
}
4. 异步IO操作
4.1 异步文件操作
use tokio::fs::File;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
async fn read_file() {
let mut file = File::open("file.txt").await.unwrap();
let mut content = String::new();
file.read_to_string(&mut content).await.unwrap();
println!("File content: {}", content);
}
async fn write_file() {
let mut file = File::create("output.txt").await.unwrap();
file.write_all(b"Hello, World!").await.unwrap();
println!("File written");
}
#[tokio::main]
async fn main() {
read_file().await;
write_file().await;
}
4.2 异步网络操作
use reqwest::Client;
async fn fetch_url() {
let client = Client::new();
let response = client.get("https://example.com").send().await.unwrap();
let content = response.text().await.unwrap();
println!("URL content length: {}", content.len());
}
#[tokio::main]
async fn main() {
fetch_url().await;
}
5. 异步流
use tokio::stream::StreamExt;
use tokio::time::{interval, Duration};
#[tokio::main]
async fn main() {
let mut interval = interval(Duration::from_millis(100));
let mut count = 0;
while let Some(_) = interval.next().await {
println!("Tick {}", count);
count += 1;
if count >= 5 {
break;
}
}
}
6. 实际应用场景
6.1 异步Web服务器
use axum::routing::get;
use axum::Router;
use tokio::time::sleep;
use tokio::time::Duration;
async fn hello() -> String {
sleep(Duration::from_secs(1)).await; // 模拟异步操作
"Hello, World!".to_string()
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(hello));
axum::Server::bind(&"127.0.0.1:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
6.2 异步爬虫
use reqwest::Client;
use tokio::join;
async fn fetch_title(client: &Client, url: &str) -> String {
let response = client.get(url).send().await.unwrap();
let content = response.text().await.unwrap();
// 简单解析标题
if let Some(start) = content.find("<title>") {
if let Some(end) = content[start..].find("</title>") {
return content[start + 7..start + end].to_string();
}
}
"No title found".to_string()
}
#[tokio::main]
async fn main() {
let client = Client::new();
let urls = [
"https://example.com",
"https://google.com",
"https://github.com"
];
let tasks = urls.iter().map(|url| fetch_title(&client, url));
let results = join!(tasks.collect::<Vec<_>>());
for (url, title) in urls.iter().zip(results.0) {
println!("Title of {}: {}", url, title);
}
}
6.3 异步数据库操作
use sqlx::postgres::PgPool;
async fn query_database() {
let pool = PgPool::connect("postgres://postgres:password@localhost/test").await.unwrap();
let rows = sqlx::query!("SELECT * FROM users").fetch_all(&pool).await.unwrap();
for row in rows {
println!("User: {} - {}", row.id, row.name);
}
}
#[tokio::main]
async fn main() {
query_database().await;
}
7. 最佳实践
- 使用
async和await:使用async定义异步函数,使用await等待 Future 完成。 - 使用
tokio::spawn:使用tokio::spawn创建任务,并行执行多个异步操作。 - 使用
join!宏:使用join!宏等待多个任务完成。 - 使用
select!宏:使用select!宏处理多个并发事件。 - 处理错误:正确处理异步操作中的错误。
- 使用超时:对于可能长时间运行的操作,使用
timeout设置超时。 - 避免阻塞操作:在异步代码中,避免使用阻塞操作,如
std::thread::sleep,应该使用tokio::time::sleep。 - 使用异步库:对于IO操作,使用异步库,如
tokio::fs、reqwest、sqlx等。
8. 总结
Rust 的异步编程模型基于 Future trait 和 async/await 语法,它允许我们编写非阻塞的代码,提高程序的性能和响应速度。通过掌握异步编程的高级应用,我们可以编写更加高效、响应速度更快的代码。
在实际应用中,异步编程可以用于Web服务器、爬虫、数据库操作等多种场景,大大提高代码的效率和响应速度。
希望本文对你理解和应用 Rust 异步编程有所帮助!
759



被折叠的 条评论
为什么被折叠?



