pub struct RateLimiter<B: CacheBackend> {
pub cache: Arc<B>,
pub limit: u32,
pub ttl: Duration,
}Expand description
The RateLimiter struct for distributed, IP-based rate limiting.
§Type Parameters:
B: A type that implements theCacheBackendtrait.
Fields§
§cache: Arc<B>The caching backend instance (e.g., Redis, in-memory, etc.).
limit: u32Maximum allowed requests within a TTL window.
ttl: DurationDuration of the rate limiting window.
Implementations§
Source§impl<B: CacheBackend> RateLimiter<B>
impl<B: CacheBackend> RateLimiter<B>
Sourcepub fn new(cache: Arc<B>, limit: u32, ttl: Duration) -> Self
pub fn new(cache: Arc<B>, limit: u32, ttl: Duration) -> Self
Constructs a new RateLimiter.
§Arguments
cache- A caching backend instance wrapped inArc.limit- Maximum number of allowed requests in the TTL window.ttl- Duration for the rate limiting window.
Sourcepub fn allow(&self, ip: &str) -> bool
pub fn allow(&self, ip: &str) -> bool
Checks whether a request from the given IP is allowed.
This method does the following:
- Builds a key using the client’s IP.
- Retrieves the current request count from the cache.
- If under the limit, increments the count.
- If this is the first request, sets the TTL for that key.
- Returns
trueif the request is allowed, orfalseif the limit is exceeded.
§Arguments
ip- A string slice representing the client’s IP address.
§Returns
trueif the request is allowed;falseotherwise.
Auto Trait Implementations§
impl<B> Freeze for RateLimiter<B>
impl<B> RefUnwindSafe for RateLimiter<B>where
B: RefUnwindSafe,
impl<B> Send for RateLimiter<B>
impl<B> Sync for RateLimiter<B>
impl<B> Unpin for RateLimiter<B>
impl<B> UnwindSafe for RateLimiter<B>where
B: RefUnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more