#rate-limiting #bucket #algorithm #api #acquire #object #ok

bin+lib tokenbucket

提供简单的 API 实现令牌桶算法

6 个版本

0.1.5 2024年5月20日
0.1.4 2024年4月9日
0.1.3 2020年8月21日

#1#ok

Download history 111/week @ 2024-05-16 27/week @ 2024-05-23 88/week @ 2024-05-30 587/week @ 2024-06-06 2878/week @ 2024-06-13 4295/week @ 2024-06-20 3652/week @ 2024-06-27 3317/week @ 2024-07-04 4642/week @ 2024-07-11 3823/week @ 2024-07-18 4762/week @ 2024-07-25 5475/week @ 2024-08-01 5021/week @ 2024-08-08 3100/week @ 2024-08-15

每月19,096 次下载

MIT 协议

13KB
101

tokenbucket

Documentation GitHub license Downloads

此库为 Rust 编程语言提供 TokenBucket 算法的实现。

安装

将以下内容添加到您的 Cargo.toml 中

[dependencies]
tokenbucket = "0.1.5"

使用方法

use tokenbucket::{TokenBucket, TokenAcquisitionResult};

fn main() {
    let mut bucket = TokenBucket::new(5.0, 100.0);
    match bucket.acquire(1.0) {
        Ok(rate)  => println!("rate/allow: {}, true", rate),
        Err(rate) => println!("rate/allow: {}, false", rate),
    }
}

有关更高级的使用示例,请参阅文档


lib.rs:

此软件包提供了一个简单的 TokenBucket 对象,用于速率限制。

简例程序

use tokenbucket::TokenBucket;
use tokenbucket::TokenAcquisitionResult;
use std::{thread, time};

// Will acquire tokens at the specified rate for the specified duration.
// After each acquisition, the AcquisitionResult will be printed.
fn run(bucket: &mut TokenBucket, rate: u32, duration: u32) {
    for _ in 0..=(rate * duration) {
        // Acquire 1 token from the bucket.
        let acquisition: TokenAcquisitionResult = bucket.acquire(1.0);

        // Determine the acquisition result.
        match acquisition {
            Ok(rate)  => println!("rate/allow: {}, true", rate),
            Err(rate) => println!("rate/allow: {}, false", rate),
        }
        
        // Sleep for enough time to match the desired rate/second.
        thread::sleep(time::Duration::from_micros(
            (1000000.0 * (1.0 / rate as f64)) as u64,
        ));
    }
}

fn main() {
    // Create the TokenBucket object
    let mut token_bucket: TokenBucket = TokenBucket::new(5.0, 100.0);

    // Start of by acquiring 60 tokens per second for 10 seconds.
    run(&mut token_bucket, 60, 10);

    // Slow down to 2 tokens per second for 10 seconds.
    run(&mut token_bucket, 2, 10);
}

无运行时依赖