use cached::ConcurrentCachedExt;
use cached::macros::concurrent_cached;
use cached::time::Duration;
use std::io;
use std::io::Write;
use thiserror::Error;
#[derive(Error, Debug, PartialEq, Clone)]
enum ExampleError {
#[error("error with disk cache `{0}`")]
DiskError(String),
}
#[concurrent_cached(
disk = true,
ttl_secs = 30,
map_error = |e| ExampleError::DiskError(format!("{e:?}"))
)]
fn cached_sleep_secs(secs: u64) -> Result<(), ExampleError> {
std::thread::sleep(Duration::from_secs(secs));
Ok(())
}
impl From<cached::RedbCacheError> for ExampleError {
fn from(e: cached::RedbCacheError) -> Self {
ExampleError::DiskError(format!("{e:?}"))
}
}
#[concurrent_cached(disk = true, ttl_secs = 30)]
fn cached_sleep_secs_from(secs: u64) -> Result<(), ExampleError> {
std::thread::sleep(Duration::from_secs(secs));
Ok(())
}
fn main() {
print!("1. first sync call with a 2 seconds sleep...");
io::stdout().flush().unwrap();
cached_sleep_secs(2).unwrap();
println!("done");
print!("second sync call with a 2 seconds sleep (it should be fast)...");
io::stdout().flush().unwrap();
cached_sleep_secs(2).unwrap();
println!("done");
CACHED_SLEEP_SECS.remove(&2).unwrap();
print!("third sync call with a 2 seconds sleep (slow, after cache-remove)...");
io::stdout().flush().unwrap();
cached_sleep_secs(2).unwrap();
println!("done");
use cached::RedbCache;
let cache: RedbCache<u64, u64> = RedbCache::builder()
.name("disk-example-flush")
.durable(false)
.build()
.unwrap();
for i in 0..3 {
cache.set(i, i * 10).unwrap();
}
cache.flush().unwrap(); println!("flushed 3 cheap writes to disk in a single durable commit");
print!("call without map_error (From<RedbCacheError>) ...");
io::stdout().flush().unwrap();
cached_sleep_secs_from(1).unwrap();
println!("done");
}