A time-to-live (TTL) cache implementation with optional background purging for expired entries.
We needed a caching implementation that would not return expired entries, while also preventing expired entries from unnecessarily inflating the cache size.
This TTL cache includes a background purge thread that will remove expired
cache entries on a specified interval. The purge thread uses tokio
to take
advantage of its write-preferring RwLock
.
```rust use std::{ sync::Arc, time::{Duration, SystemTime}, };
use tokio::{sync::RwLock, time::interval}; use ttlcachewithpurging::{cache::TtlCache, purging::startperiodic_purge};
const MININSECS: u64 = 60; const HOURINSECS: u64 = 60 * MININSECS;
async fn main() { // Cache setup let cache = Arc::new(RwLock::new(TtlCache::new())); let purgeinterval = interval(Duration::fromsecs(MININSECS)); startperiodicpurge(cache.clone(), purge_interval);
// Add entries
let key = "key1";
let val = "val1";
let expires_at = SystemTime::now()
.checked_add(Duration::from_secs(HOUR_IN_SECS))
.unwrap();
cache.write().await.insert(key, val, expires_at);
// Read entries
let _cached_val = cache.read().await.get(key).unwrap();
let (_cached_val, _expires_at) = cache.read().await.get_value_and_expiration(key).unwrap();
} ```
Licensed under either of
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
All behavior is governed by the Rust Code of Conduct.