Crate async_rate_limiter
source ·Expand description
async-rate-limiter implements a token bucket algorithm that can be used to limit API access frequency.
§Example
Update your Cargo.toml:
[dependencies]
# Change features to ["rt-async-std"] if you are using async-std runtime.
async-rate-limiter = { version = "1.39.2", features = ["rt-tokio"] }
Thanks to Rust’s async functionality, this crate is very simple to use.
Just put your function call after RateLimiter::acquire().await, then
the function will be called with the specified rate limit.
Here is a simple example:
use async_rate_limiter::RateLimiter;
use std::time::Duration;
#[tokio::main]
async fn main() {
let mut rl = RateLimiter::new(3, 5);
let ok = rl.acquire(None).await;
assert!(ok);
println!("Do something that you want to limit the rate ...");
// acquire with a timeout
let ok = rl.acquire(Some(Duration::from_secs(10))).await;
if ok {
println!("Do something that you want to limit the rate ...");
}
}
async-rate-limiter can support different async runtimes, tokio & async-std are supported currently. You can use features to switch async runtimes.