pub struct MokaCacheBuilder<K, V, C> { /* private fields */ }
Available on crate feature manager-moka only.
Expand description

Builds a Cache with various configuration knobs.

Example: Expirations

// Cargo.toml
//
// [dependencies]
// moka = { version = "0.12", features = ["future"] }
// tokio = { version = "1", features = ["rt-multi-thread", "macros" ] }
// futures = "0.3"

use moka::future::Cache;
use std::time::Duration;

#[tokio::main]
async fn main() {
    let cache = Cache::builder()
        // Max 10,000 entries
        .max_capacity(10_000)
        // Time to live (TTL): 30 minutes
        .time_to_live(Duration::from_secs(30 * 60))
        // Time to idle (TTI):  5 minutes
        .time_to_idle(Duration::from_secs( 5 * 60))
        // Create the cache.
        .build();

    // This entry will expire after 5 minutes (TTI) if there is no get().
    cache.insert(0, "zero").await;

    // This get() will extend the entry life for another 5 minutes.
    cache.get(&0);

    // Even though we keep calling get(), the entry will expire
    // after 30 minutes (TTL) from the insert().
}

Implementations§

§

impl<K, V> CacheBuilder<K, V, Cache<K, V>>
where K: Eq + Hash + Send + Sync + 'static, V: Clone + Send + Sync + 'static,

pub fn new(max_capacity: u64) -> CacheBuilder<K, V, Cache<K, V>>

Construct a new CacheBuilder that will be used to build a Cache holding up to max_capacity entries.

pub fn build(self) -> Cache<K, V>

Builds a Cache<K, V>.

Panics

Panics if configured with either time_to_live or time_to_idle higher than 1000 years. This is done to protect against overflow when computing key expiration.

pub fn build_with_hasher<S>(self, hasher: S) -> Cache<K, V, S>
where S: BuildHasher + Clone + Send + Sync + 'static,

Builds a Cache<K, V, S> with the given hasher of type S.

Examples

This example uses AHash hasher from AHash crate.

// Cargo.toml
// [dependencies]
// ahash = "0.8"
// moka = { version = ..., features = ["future"] }
// tokio = { version = "1", features = ["rt-multi-thread", "macros" ] }

use moka::future::Cache;

#[tokio::main]
async fn main() {
    // The type of this cache is: Cache<i32, String, ahash::RandomState>
    let cache = Cache::builder()
        .max_capacity(100)
        .build_with_hasher(ahash::RandomState::default());
    cache.insert(1, "one".to_string()).await;
}

Note: If you need to add a type annotation to your cache, you must use the form of Cache<K, V, S> instead of Cache<K, V>. That S is the type of the build hasher, and its default is the RandomState from std::collections::hash_map module . If you use a different build hasher, you must specify S explicitly.

Here is a good example:

struct Good {
    // Specifying the type in Cache<K, V, S> format.
    cache: Cache<i32, String, ahash::RandomState>,
}

// Storing the cache from above example. This should compile.
Good { cache };

Here is a bad example. This struct cannot store the above cache because it does not specify S:

struct Bad {
    // Specifying the type in Cache<K, V> format.
    cache: Cache<i32, String>,
}

// This should not compile.
Bad { cache };
// => error[E0308]: mismatched types
//    expected struct `std::collections::hash_map::RandomState`,
//       found struct `ahash::RandomState`
Panics

Panics if configured with either time_to_live or time_to_idle higher than 1000 years. This is done to protect against overflow when computing key expiration.

§

impl<K, V, C> CacheBuilder<K, V, C>

pub fn name(self, name: &str) -> CacheBuilder<K, V, C>

Sets the name of the cache. Currently the name is used for identification only in logging messages.

pub fn max_capacity(self, max_capacity: u64) -> CacheBuilder<K, V, C>

Sets the max capacity of the cache.

pub fn initial_capacity(self, number_of_entries: usize) -> CacheBuilder<K, V, C>

Sets the initial capacity (number of entries) of the cache.

pub fn weigher( self, weigher: impl Fn(&K, &V) -> u32 + Send + Sync + 'static ) -> CacheBuilder<K, V, C>

Sets the weigher closure to the cache.

The closure should take &K and &V as the arguments and returns a u32 representing the relative size of the entry.

pub fn eviction_listener<F>(self, listener: F) -> CacheBuilder<K, V, C>
where F: Fn(Arc<K>, V, RemovalCause) + Send + Sync + 'static,

Sets the eviction listener closure to the cache. The closure should take Arc<K>, V and RemovalCause as the arguments.

See this example for a usage of eviction listener.

Sync or Async Eviction Listener

The closure can be either synchronous or asynchronous, and CacheBuilder provides two methods for setting the eviction listener closure:

  • If you do not need to .await anything in the eviction listener, use this eviction_listener method.
  • If you need to .await something in the eviction listener, use async_eviction_listener method instead.
Panics

It is very important to make the listener closure not to panic. Otherwise, the cache will stop calling the listener after a panic. This is an intended behavior because the cache cannot know whether is is memory safe or not to call the panicked lister again.

pub fn async_eviction_listener<F>(self, listener: F) -> CacheBuilder<K, V, C>
where F: Fn(Arc<K>, V, RemovalCause) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync + 'static,

Sets the eviction listener closure to the cache. The closure should take Arc<K>, V and RemovalCause as the arguments, and return a ListenerFuture.

See this example for a usage of asynchronous eviction listener.

Sync or Async Eviction Listener

The closure can be either synchronous or asynchronous, and CacheBuilder provides two methods for setting the eviction listener closure:

  • If you do not need to .await anything in the eviction listener, use eviction_listener method instead.
  • If you need to .await something in the eviction listener, use this method.
Panics

It is very important to make the listener closure not to panic. Otherwise, the cache will stop calling the listener after a panic. This is an intended behavior because the cache cannot know whether is is memory safe or not to call the panicked lister again.

pub fn time_to_live(self, duration: Duration) -> CacheBuilder<K, V, C>

Sets the time to live of the cache.

A cached entry will be expired after the specified duration past from insert.

Panics

CacheBuilder::build* methods will panic if the given duration is longer than 1000 years. This is done to protect against overflow when computing key expiration.

pub fn time_to_idle(self, duration: Duration) -> CacheBuilder<K, V, C>

Sets the time to idle of the cache.

A cached entry will be expired after the specified duration past from get or insert.

Panics

CacheBuilder::build* methods will panic if the given duration is longer than 1000 years. This is done to protect against overflow when computing key expiration.

pub fn expire_after( self, expiry: impl Expiry<K, V> + Send + Sync + 'static ) -> CacheBuilder<K, V, C>

Sets the given expiry to the cache.

See the example for per-entry expiration policy in the Cache documentation.

pub fn support_invalidation_closures(self) -> CacheBuilder<K, V, C>

Enables support for Cache::invalidate_entries_if method.

The cache will maintain additional internal data structures to support invalidate_entries_if method.

Trait Implementations§

§

impl<K, V> Default for CacheBuilder<K, V, Cache<K, V>>
where K: Eq + Hash + Send + Sync + 'static, V: Clone + Send + Sync + 'static,

§

fn default() -> CacheBuilder<K, V, Cache<K, V>>

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

Auto Trait Implementations§

§

impl<K, V, C> !RefUnwindSafe for CacheBuilder<K, V, C>

§

impl<K, V, C> Send for CacheBuilder<K, V, C>
where C: Send,

§

impl<K, V, C> Sync for CacheBuilder<K, V, C>
where C: Sync,

§

impl<K, V, C> Unpin for CacheBuilder<K, V, C>
where C: Unpin,

§

impl<K, V, C> !UnwindSafe for CacheBuilder<K, V, C>

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.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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.

§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

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

§

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>,

§

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.
§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more