pub struct Cache { /* private fields */ }Expand description
The main cache facade for storing and retrieving cached values.
Provides a driver-agnostic API. Create with Cache::memory() or Cache::redis().
§Thread Safety
The Cache is Send + Sync and can be safely shared across async tasks
and Axum handlers via Arc or Axum’s State.
Implementations§
Source§impl Cache
impl Cache
Sourcepub fn memory() -> Self
pub fn memory() -> Self
Create a cache backed by an in-memory DashMap. Zero configuration.
Data is lost on process restart. Perfect for development and single-instance apps.
Sourcepub fn custom(driver: Box<dyn CacheDriver>) -> Self
pub fn custom(driver: Box<dyn CacheDriver>) -> Self
Create a cache from any custom driver implementing CacheDriver.
Sourcepub async fn get(&self, key: &str) -> Result<Option<Arc<String>>, CacheError>
pub async fn get(&self, key: &str) -> Result<Option<Arc<String>>, CacheError>
Retrieve a value by key.
Sourcepub async fn put(
&self,
key: &str,
value: &str,
ttl_secs: Option<u64>,
) -> Result<(), CacheError>
pub async fn put( &self, key: &str, value: &str, ttl_secs: Option<u64>, ) -> Result<(), CacheError>
Store a value with an optional TTL in seconds.
Pass None for TTL to store indefinitely. The in-memory driver also
stores a TTL too large for the monotonic clock (such as u64::MAX)
without expiry.
Sourcepub async fn flush(&self) -> Result<(), CacheError>
pub async fn flush(&self) -> Result<(), CacheError>
Remove all keys from the cache.
Sourcepub async fn has(&self, key: &str) -> Result<bool, CacheError>
pub async fn has(&self, key: &str) -> Result<bool, CacheError>
Check if a key exists and has not expired.
Sourcepub async fn inspect(&self, limit: usize) -> Result<CacheInspection, CacheError>
pub async fn inspect(&self, limit: usize) -> Result<CacheInspection, CacheError>
Returns a bounded metadata-only snapshot when supported by the driver.
Sourcepub async fn remember<F, Fut>(
&self,
key: &str,
ttl_secs: u64,
f: F,
) -> Result<Arc<String>, CacheError>
pub async fn remember<F, Fut>( &self, key: &str, ttl_secs: u64, f: F, ) -> Result<Arc<String>, CacheError>
Retrieve a cached value, or compute it with the provided closure and cache the result.
This is the cache-aside (or “remember”) pattern — the most common caching strategy.
§Example
use std::sync::Arc;
use rullst_core::cache::{Cache, CacheError};
async fn load_bio(cache: &Cache) -> Result<Arc<String>, CacheError> {
cache.remember("user:42:bio", 300, || async {
Ok("Example biography".to_string())
}).await
}