Tower 服务抽象
问题
Tower 是什么?在 Rust 网络编程中扮演什么角色?
答案
Tower 是一个通用的服务抽象框架,定义了 Service trait 作为请求-响应模式的统一接口。axum、tonic、hyper 都基于 Tower 构建。
Service trait
pub trait Service<Request> {
type Response;
type Error;
type Future: Future<Output = Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>;
fn call(&mut self, req: Request) -> Self::Future;
}
核心思想:任何请求进 → 响应出的东西都是 Service。
中间件(Layer)
Tower 的中间件通过 Layer 组合:
use tower::{ServiceBuilder, timeout::TimeoutLayer, limit::RateLimitLayer};
use std::time::Duration;
// 组合多个中间件
let service = ServiceBuilder::new()
.layer(TimeoutLayer::new(Duration::from_secs(30))) // 超时
.layer(RateLimitLayer::new(100, Duration::from_secs(1))) // 限流
.service(my_handler);
在 axum 中使用
use axum::{Router, routing::get, middleware};
use tower_http::{
cors::CorsLayer,
compression::CompressionLayer,
trace::TraceLayer,
};
let app = Router::new()
.route("/api/users", get(list_users))
.layer(CorsLayer::permissive())
.layer(CompressionLayer::new())
.layer(TraceLayer::new_for_http());
常用 Tower 中间件
| 中间件 | crate | 功能 |
|---|---|---|
| 超时 | tower::timeout | 请求超时 |
| 限流 | tower::limit | 速率限制 |
| 重试 | tower::retry | 失败重试 |
| 缓冲 | tower::buffer | 请求缓冲 |
| CORS | tower-http | 跨域处理 |
| 压缩 | tower-http | 响应压缩 |
| 追踪 | tower-http | 请求日志 |
常见面试问题
Q1: 为什么 Tower 是 Rust Web 生态的基石?
答案:
Tower 提供了统一的 Service 抽象,使得中间件可以在不同框架间复用:
- axum 路由是 Service
- tonic gRPC 处理器是 Service
- hyper HTTP 处理器是 Service
一个 TimeoutLayer 可以同时用于 HTTP 和 gRPC,这就是统一抽象的价值。类似于前端的中间件模式,但通过类型系统保证了组合安全性。