#rate-limiting #tokio #rate #async-context #limiting #async #sliding-window

async-rate-limit

异步环境中的限速常见特性和实现

3个不稳定版本

0.1.0 2024年6月19日
0.0.4 2024年3月8日
0.0.3 2023年10月4日

#476 in 异步

Download history 13/week @ 2024-04-14 31/week @ 2024-04-21 20/week @ 2024-04-28 9/week @ 2024-05-05 6/week @ 2024-05-12 22/week @ 2024-05-19 31/week @ 2024-05-26 23/week @ 2024-06-02 14/week @ 2024-06-09 170/week @ 2024-06-16 33/week @ 2024-06-23 43/week @ 2024-06-30 53/week @ 2024-07-07 38/week @ 2024-07-14 27/week @ 2024-07-21 64/week @ 2024-07-28

183 每月下载量
用于 kraken-async-rs

MIT 许可证

27KB
374

async-rate-limit

一个基本的Tokio限速库,提供两个特性和常用实现。

badge License: MIT

用法

use tokio::time::{Instant, Duration};
use async_rate_limit::limiters::VariableCostRateLimiter;
use async_rate_limit::sliding_window::SlidingWindowRateLimiter;

#[tokio::main]
async fn main() -> () {
    let mut limiter = SlidingWindowRateLimiter::new(Duration::from_secs(1), 5);
    
    for _ in 0..3 {
        // these will proceed immediately, spending 3 units
        get_lite(&mut limiter).await;
    }
    // 3/5 units are spent, so this will wait for ~1s to proceed since it costs another 3
    get_heavy(&mut limiter).await;
}

// note the use of the `VariableCostRateLimiter` trait, rather than the direct type
async fn get_lite<T>(limiter: &mut T) where T: VariableCostRateLimiter {
    limiter.wait_with_cost(1).await;
    println!("Lite: {:?}", Instant::now());
}

async fn get_heavy<T>(limiter: &mut T) where T: VariableCostRateLimiter {
    limiter.wait_with_cost(3).await;
    println!("Heavy: {:?}", Instant::now());
}

依赖项

~2.4–8.5MB
~58K SLoC