1 个不稳定版本
0.1.0 | 2024 年 5 月 23 日 |
---|
#9 in #ratio
17KB
244 行
识别当 Tokio 工作员过于繁忙而无法处理更多工作时的情况。
监控 Tokio 工作员的繁忙比例
TooBusy
允许您跟踪 Tokio 工作员的繁忙比例,并在它们过于繁忙时相应地做出反应。
在下面的示例中,创建并使用了一个 TooBusy
来评估 Tokio 工作员的繁忙比例,并在繁忙比例超过低水位阈值时逐步拒绝请求
use axum::{
extract::{Request, State},
http::StatusCode,
middleware::{self, Next},
response::{IntoResponse, Response},
routing::get,
Router,
};
use tokio::time::Duration;
use tokio_too_busy::*;
#[derive(Clone)]
struct AppState {
too_busy: TooBusy,
}
async fn root() -> &'static str {
"Hello, World!"
}
async fn my_middleware(State(state): State<AppState>, request: Request, next: Next) -> Response {
if state.too_busy.eval() {
return (StatusCode::SERVICE_UNAVAILABLE, "Server is too busy").into_response();
}
next.run(request).await
}
#[tokio::main(flavor = "multi_thread", worker_threads = 1)]
async fn main() {
let too_busy = TooBusy::builder()
.interval(Duration::from_secs(1))
.ewma_alpha(0.1)
.high_watermark(95)
.low_watermark(90)
.build();
let state = AppState { too_busy };
let app = Router::new()
.route("/", get(root))
.route_layer(middleware::from_fn_with_state(state.clone(), my_middleware))
.with_state(state);
let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
依赖项
~2.2–3.5MB
~52K SLoC