pub struct Cache<T> { /* private fields */ }Expand description
A policy that caches successful results for a specified duration.
The cache stores the result of the first successful execution and returns it for subsequent calls until the TTL expires.
§Note
This is a simple single-value cache. For more sophisticated caching (keyed cache, LRU eviction, etc.), consider using a dedicated caching library.
§Examples
use do_over::{policy::Policy, cache::Cache, error::DoOverError};
use std::time::Duration;
let cache = Cache::<String>::new(Duration::from_secs(300));
// First call - executes operation
let result: Result<String, DoOverError<String>> = cache.execute(|| async {
Ok("data".to_string())
}).await;
// Second call - returns cached value
let result: Result<String, DoOverError<String>> = cache.execute(|| async {
panic!("This won't be called!");
}).await;Implementations§
Source§impl<T> Cache<T>
impl<T> Cache<T>
Sourcepub fn new(ttl: Duration) -> Self
pub fn new(ttl: Duration) -> Self
Create a new cache policy.
§Arguments
ttl- Time-to-live for cached values
§Examples
use do_over::cache::Cache;
use std::time::Duration;
// Cache for 5 minutes
let cache = Cache::<String>::new(Duration::from_secs(300));
// Cache for 1 hour
let cache = Cache::<Vec<u8>>::new(Duration::from_secs(3600));Sourcepub async fn invalidate(&self)
pub async fn invalidate(&self)
Clear the cached value.
The next execution will call the underlying operation.
Sourcepub async fn has_cached_value(&self) -> bool
pub async fn has_cached_value(&self) -> bool
Check if there’s a valid cached value.
Trait Implementations§
Auto Trait Implementations§
impl<T> Freeze for Cache<T>
impl<T> !RefUnwindSafe for Cache<T>
impl<T> Send for Cache<T>
impl<T> Sync for Cache<T>
impl<T> Unpin for Cache<T>
impl<T> !UnwindSafe for Cache<T>
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