2026年03月27日-Rust高性能系统编程实战 一、Rust所有权系统深度解析 1.1 核心概念:所有权、借用与生命周期 Rust的所有权系统是其最独特的特性,它实现了内存安全而无需垃圾回收。 1.2 智能指针应用 二、并发编程模式 2.1 线程与消息传递 2.2 共享状态并发 三、异步编程与Tokio 3.1 异步基础 3.2 Tokio异步运行时 四、高性能Web服务 4.1 使用Actix-web构建REST API 4.2 数据库连接池 五、性能优化技巧 5.1 零拷贝与迭代器 5.
Rust的所有权系统是其最独特的特性,它实现了内存安全而无需垃圾回收。
// 所有权基本规则演示 fn main() { // 规则1:每个值有一个所有者 let s1 = String::from("Hello"); let s2 = s1; // s1的所有权转移给s2,s1不再有效 // println!("{}", s1); // 编译错误:value borrowed here after move // 规则2:同一时间只能有一个所有者 let x = 5; let y = x; // 实现了Copy trait的类型,会自动复制 println!("x={}, y={}", x, y); // 正确:x仍然有效 // 规则3:所有者离开作用域时,值被丢弃 { let s = String::from("ownership"); } // s在这里被自动drop,内存被释放 } // 借用规则演示 fn calculate_length(s: &String) -> usize { // 借用String s.len() } // s离开作用域,但因为它不拥有值,所以不会drop fn main() { let s1 = String::from("Hello, world!"); let len = calculate_length(&s1); // 传递引用 println!("The length of '{}' is {}.", s1, len); // s1仍然有效 } // 可变借用演示 fn append_world(s: &mut String) { s.push_str(", world!"); } fn main() { let mut s = String::from("Hello"); append_world(&mut s); println!("{}", s); // 输出: Hello, world! } // 生命周期注解 fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } } fn main() { let string1 = String::from("long string is long"); let string2 = String::from("xyz"); let result = longest(string1.as_str(), string2.as_str()); println!("The longest string is {}", result); }
use std::rc::Rc; use std::cell::RefCell; // Rc<T> - 引用计数智能指针 enum List { Cons(i32, Rc<List>), Nil, } use List::{Cons, Nil}; fn main() { let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); let b = Cons(3, Rc::clone(&a)); // 增加引用计数 let c = Cons(4, Rc::clone(&a)); // 再次增加引用计数 println!("Count after creating b: {}", Rc::strong_count(&a)); println!("Count after creating c: {}", Rc::strong_count(&a)); } // RefCell<T> - 内部可变性 pub trait Messenger { fn send(&self, msg: &str); } pub struct LimitTracker<'a, T: Messenger> { messenger: &'a T, value: usize, max: usize, } impl<'a, T> LimitTracker<'a, T> where T: Messenger, { pub fn new(messenger: &'a T, max: usize) -> LimitTracker<'a, T> { LimitTracker { messenger, value: 0, max, } } pub fn set_value(&mut self, value: usize) { self.value = value; let percentage = self.value as f64 / self.max as f64; if percentage >= 1.0 { self.messenger.send("Error: You are over your quota!"); } else if percentage >= 0.9 { self.messenger.send("Urgent: You're at 90% of your quota"); } else if percentage >= 0.75 { self.messenger.send("Warning: You're at 75% of your quota"); } } } #[cfg(test)] mod tests { use super::*; use std::cell::RefCell; struct MockMessenger { sent_messages: RefCell<Vec<String>>, } impl MockMessenger { fn new() -> MockMessenger { MockMessenger { sent_messages: RefCell::new(vec![]), } } } impl Messenger for MockMessenger { fn send(&self, message: &str) { self.sent_messages.borrow_mut().push(String::from(message)); } } #[test] fn it_sends_an_over_75_percent_warning_message() { let mock_messenger = MockMessenger::new(); let mut limit_tracker = LimitTracker::new(&mock_messenger, 100); limit_tracker.set_value(80); assert_eq!(mock_messenger.sent_messages.borrow().len(), 1); } }
use std::thread; use std::time::Duration; use std::sync::mpsc; // 消息传递模式 fn main() { // 创建通道 let (tx, rx) = mpsc::channel(); // 创建生产者线程 thread::spawn(move || { let vals = vec![ String::from("hi"), String::from("from"), String::from("the"), String::from("thread"), ]; for val in vals { tx.send(val).unwrap(); thread::sleep(Duration::from_secs(1)); } }); // 主线程接收消息 for received in rx { println!("Got: {}", received); } } // 多生产者单消费者 use std::sync::mpsc; fn main() { let (tx, rx) = mpsc::channel(); let tx1 = tx.clone(); thread::spawn(move || { let vals = vec![ String::from("hi"), String::from("from"), String::from("the"), String::from("thread"), ]; for val in vals { tx1.send(val).unwrap(); thread::sleep(Duration::from_secs(1)); } }); thread::spawn(move || { let vals = vec![ String::from("more"), String::from("messages"), String::from("for"), String::from("you"), ]; for val in vals { tx.send(val).unwrap(); thread::sleep(Duration::from_secs(1)); } }); for received in rx { println!("Got: {}", received); } }
use std::sync::{Arc, Mutex}; use std::thread; fn main() { // Arc<T> - 原子引用计数,用于线程间共享 // Mutex<T> - 互斥锁,确保同一时间只有一个线程能访问数据 let counter = Arc::new(Mutex::new(0)); let mut handles = vec![]; for _ in 0..10 { let counter = Arc::clone(&counter); let handle = thread::spawn(move || { let mut num = counter.lock().unwrap(); *num += 1; }); handles.push(handle); } for handle in handles { handle.join().unwrap(); } println!("Result: {}", *counter.lock().unwrap()); } // 读写锁(RwLock) use std::sync::RwLock; fn main() { let lock = RwLock::new(5); // 多个读锁可以同时持有 { let r1 = lock.read().unwrap(); let r2 = lock.read().unwrap(); println!("Read locks: {}, {}", r1, r2); } // 读锁在这里释放 // 写锁是独占的 { let mut w = lock.write().unwrap(); *w += 1; println!("Write lock: {}", w); } // 写锁在这里释放 }
use std::future::Future; use std::pin::Pin; use std::task::{Context, Poll}; // 自定义Future实现 struct Delay { when: Instant, } impl Future for Delay { type Output = &'static str; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<&'static str> { if Instant::now() >= self.when { Poll::Ready("done") } else { // 获取Waker并在准备就绪时唤醒任务 cx.waker().wake_by_ref(); Poll::Pending } } } use std::time::{Duration, Instant}; async fn delay(duration: Duration) -> &'static str { // 使用Tokio的定时器 tokio::time::sleep(duration).await; "done" } #[tokio::main] async fn main() { println!("Hello"); delay(Duration::from_secs(1)).await; println!("World!"); }
use tokio::net::TcpListener; use tokio::io::{AsyncReadExt, AsyncWriteExt}; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { // 创建TCP监听器 let listener = TcpListener::bind("127.0.0.1:8080").await?; loop { // 接受连接 let (mut socket, _) = listener.accept().await?; // 为每个连接生成一个任务 tokio::spawn(async move { let mut buf = [0; 1024]; loop { let n = match socket.read(&mut buf).await { Ok(n) if n == 0 => return, Ok(n) => n, Err(e) => { eprintln!("failed to read from socket; err = {:?}", e); return; } }; if let Err(e) = socket.write_all(&buf[0..n]).await { eprintln!("failed to write to socket; err = {:?}", e); return; } } }); } } // 异步文件操作 use tokio::fs::File; use tokio::io::AsyncWriteExt; async fn write_file() -> Result<(), Box<dyn std::error::Error>> { let mut file = File::create("foo.txt").await?; file.write_all(b"Hello, world!").await?; Ok(()) } // 异步HTTP服务器 use tokio::net::TcpListener; use tokio::io::{AsyncReadExt, AsyncWriteExt}; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let listener = TcpListener::bind("127.0.0.1:8080").await?; loop { let (mut socket, _) = listener.accept().await?; tokio::spawn(async move { let mut buf = [0; 1024]; // 读取请求 let n = socket.read(&mut buf).await?; // 构造HTTP响应 let response = "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello, World!"; // 发送响应 socket.write_all(response.as_bytes()).await?; Ok::<_, Box<dyn std::error::Error>>(()) }); } }
use actix_web::{web, App, HttpResponse, HttpServer, Responder}; use serde::{Deserialize, Serialize}; // 数据模型 #[derive(Serialize, Deserialize)] struct User { id: u32, name: String, email: String, } #[derive(Serialize)] struct Response { status: String, message: String, } // 健康检查 async fn health_check() -> impl Responder { HttpResponse::Ok().json(Response { status: "ok".to_string(), message: "Service is healthy".to_string(), }) } // 获取用户列表 async fn get_users() -> impl Responder { let users = vec![ User { id: 1, name: "Alice".to_string(), email: "alice@example.com".to_string(), }, User { id: 2, name: "Bob".to_string(), email: "bob@example.com".to_string(), }, ]; HttpResponse::Ok().json(users) } // 创建用户 async fn create_user(user: web::Json<User>) -> impl Responder { println!("Received user: {:?}", user); HttpResponse::Created().json(Response { status: "success".to_string(), message: "User created successfully".to_string(), }) } // 获取单个用户 async fn get_user(path: web::Path<u32>) -> impl Responder { let user_id = path.into_inner(); let user = User { id: user_id, name: "John Doe".to_string(), email: "john@example.com".to_string(), }; HttpResponse::Ok().json(user) } #[actix_web::main] async fn main() -> std::io::Result<()> { println!("Starting server at http://127.0.0.1:8080"); HttpServer::new(|| { App::new() .route("/health", web::get().to(health_check)) .route("/users", web::get().to(get_users)) .route("/users", web::post().to(create_user)) .route("/users/{id}", web::get().to(get_user)) }) .bind("127.0.0.1:8080")? .run() .await }
use sqlx::postgres::PgPoolOptions; use sqlx::postgres::PgPool; use std::time::Duration; // 数据库模型 #[derive(Debug)] struct User { id: i32, name: String, email: String, } async fn create_pool() -> Result<PgPool, sqlx::Error> { PgPoolOptions::new() .max_connections(5) .acquire_timeout(Duration::from_secs(30)) .connect("postgresql://user:password@localhost/database") .await } async fn get_user(pool: &PgPool, user_id: i32) -> Result<Option<User>, sqlx::Error> { sqlx::query_as::<_, User>( "SELECT id, name, email FROM users WHERE id = $1" ) .bind(user_id) .fetch_optional(pool) .await } async fn create_user(pool: &PgPool, name: &str, email: &str) -> Result<User, sqlx::Error> { sqlx::query_as::<_, User>( "INSERT INTO users (name, email) VALUES ($1, $2) RETURNING *" ) .bind(name) .bind(email) .fetch_one(pool) .await } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let pool = create_pool().await?; // 创建用户 let user = create_user(&pool, "Alice", "alice@example.com").await?; println!("Created user: {:?}", user); // 查询用户 let found_user = get_user(&pool, user.id).await?; println!("Found user: {:?}", found_user); Ok(()) }
// 避免不必要的分配 use std::io::{self, Read}; fn bad_way(input: &str) -> String { // 创建多个中间String input.lines() .map(|line| line.to_uppercase()) .collect::<Vec<_>>() .join("\n") } fn good_way(input: &str) -> String { // 使用迭代器链,减少分配 input.lines() .map(|line| line.to_uppercase()) .collect::<Vec<_>>() .join("\n") } // 使用Cow避免克隆 use std::borrow::Cow; fn process_string(s: &str) -> Cow<str> { if s.contains("special") { Cow::Owned(s.replace("special", "replaced")) } else { Cow::Borrowed(s) } } // 惰性求值 use std::iter::repeat; fn main() { // 无限迭代器但只在需要时计算 let numbers = repeat(1).take(5); let sum: i32 = numbers.sum(); println!("Sum: {}", sum); }
use rayon::prelude::*; fn process_data_parallel(data: Vec<i32>) -> Vec<i32> { data.par_iter() // 并行迭代器 .map(|x| x * x) .collect() } fn main() { let data: Vec<i32> = (1..=1_000_000).collect(); let start = std::time::Instant::now(); let result = process_data_parallel(data); let duration = start.elapsed(); println!("Processed {} items in {:?}", result.len(), duration); }
use tokio::sync::mpsc; use tokio::fs::OpenOptions; use tokio::io::AsyncWriteExt; use std::time::{SystemTime, UNIX_EPOCH}; #[derive(Debug)] enum LogLevel { INFO, WARNING, ERROR, } struct LogEntry { timestamp: u64, level: LogLevel, message: String, } struct Logger { sender: mpsc::UnboundedSender<LogEntry>, } impl Logger { fn new(filename: &str) -> Self { let (sender, mut receiver) = mpsc::unbounded_channel::<LogEntry>(); // 启动写入任务 let filename = filename.to_string(); tokio::spawn(async move { let mut file = OpenOptions::new() .create(true) .append(true) .open(&filename) .await .expect("Failed to open log file"); while let Some(entry) = receiver.recv().await { let log_line = format!( "[{}] {:?}: {}\n", entry.timestamp, entry.level, entry.message ); if let Err(e) = file.write_all(log_line.as_bytes()).await { eprintln!("Failed to write log: {}", e); } } }); Logger { sender } } fn log(&self, level: LogLevel, message: &str) { let entry = LogEntry { timestamp: SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_secs(), level, message: message.to_string(), }; self.sender.send(entry).ok(); } } #[tokio::main] async fn main() { let logger = Logger::new("app.log"); // 模拟多个线程同时写入日志 let handles: Vec<_> = (0..10) .map(|i| { let logger = logger.clone(); tokio::spawn(async move { for j in 0..1000 { logger.log( LogLevel::INFO, &format!("Thread {} - Message {}", i, j) ); } }) }) .collect(); for handle in handles { handle.await.unwrap(); } println!("Logging complete. Check app.log"); }
Rust语言通过其独特的所有权系统、类型安全和零成本抽象,为构建高性能、高可靠性的系统提供了强大的工具:
Rust特别适合构建系统级应用、Web服务、数据库引擎、区块链等对性能和可靠性要求极高的场景。