CacheConfigBuilder

Struct CacheConfigBuilder 

Source
pub struct CacheConfigBuilder<Req, K> { /* private fields */ }
Expand description

Builder for configuring and constructing a cache.

Implementations§

Source§

impl<Req, K> CacheConfigBuilder<Req, K>
where K: Hash + Eq + Clone + Send + 'static,

Source

pub fn new() -> Self

Creates a new builder with default values.

Source

pub fn max_size(self, size: usize) -> Self

Sets the maximum number of entries in the cache.

Default: 100

Source

pub fn ttl(self, ttl: Duration) -> Self

Sets the time-to-live for cached entries.

If set, entries will expire after the specified duration. Default: None (no expiration)

Source

pub fn key_extractor<F>(self, f: F) -> Self
where F: Fn(&Req) -> K + Send + Sync + 'static,

Sets the function that extracts a cache key from a request.

This function must be provided before building.

Source

pub fn name(self, name: impl Into<String>) -> Self

Sets the name of this cache instance for observability.

Default: "<unnamed>"

Source

pub fn on_hit<F>(self, f: F) -> Self
where F: Fn() + Send + Sync + 'static,

Registers a callback when a cache hit occurs.

A cache hit occurs when a requested entry is found in the cache and has not expired.

§Callback Signature

Fn() - Called with no parameters when a cache hit is detected.

§Example
use tower_resilience_cache::CacheConfig;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

#[derive(Clone, Hash, Eq, PartialEq)]
struct Request {
    id: String,
}

let hit_count = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&hit_count);

let config = CacheConfig::<Request, String>::builder()
    .key_extractor(|req| req.id.clone())
    .on_hit(move || {
        let count = counter.fetch_add(1, Ordering::SeqCst);
        println!("Cache hit #{}", count + 1);
    })
    .build();
Source

pub fn on_miss<F>(self, f: F) -> Self
where F: Fn() + Send + Sync + 'static,

Registers a callback when a cache miss occurs.

A cache miss occurs when a requested entry is not found in the cache or has expired. The underlying service will be called to fetch the value, which will then be cached.

§Callback Signature

Fn() - Called with no parameters when a cache miss is detected.

§Example
use tower_resilience_cache::CacheConfig;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

#[derive(Clone, Hash, Eq, PartialEq)]
struct Request {
    id: String,
}

let miss_count = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&miss_count);

let config = CacheConfig::<Request, String>::builder()
    .key_extractor(|req| req.id.clone())
    .on_miss(move || {
        let count = counter.fetch_add(1, Ordering::SeqCst);
        println!("Cache miss #{} - fetching from service", count + 1);
    })
    .build();
Source

pub fn on_eviction<F>(self, f: F) -> Self
where F: Fn() + Send + Sync + 'static,

Registers a callback when an entry is evicted from the cache.

Eviction occurs when:

  • The cache reaches its maximum size and needs to make room for new entries
  • An entry expires due to TTL (time-to-live) configuration
§Callback Signature

Fn() - Called with no parameters when a cache eviction occurs.

§Example
use tower_resilience_cache::CacheConfig;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;

#[derive(Clone, Hash, Eq, PartialEq)]
struct Request {
    id: String,
}

let eviction_count = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&eviction_count);

let config = CacheConfig::<Request, String>::builder()
    .key_extractor(|req| req.id.clone())
    .max_size(100)
    .ttl(Duration::from_secs(300))
    .on_eviction(move || {
        let count = counter.fetch_add(1, Ordering::SeqCst);
        println!("Entry evicted (total: {})", count + 1);
    })
    .build();
Source

pub fn build(self) -> CacheLayer<Req, K>

Builds the cache layer.

§Panics

Panics if key_extractor was not set.

Trait Implementations§

Source§

impl<Req, K> Default for CacheConfigBuilder<Req, K>
where K: Hash + Eq + Clone + Send + 'static,

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<Req, K> Freeze for CacheConfigBuilder<Req, K>

§

impl<Req, K> !RefUnwindSafe for CacheConfigBuilder<Req, K>

§

impl<Req, K> Send for CacheConfigBuilder<Req, K>

§

impl<Req, K> Sync for CacheConfigBuilder<Req, K>

§

impl<Req, K> Unpin for CacheConfigBuilder<Req, K>

§

impl<Req, K> !UnwindSafe for CacheConfigBuilder<Req, K>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.