Getting Started
The quickest way to understand HydraCache is to build one local cache flow:
- create a cache;
- store a typed value with tags and TTL;
- load a missing value through
get_or_load; - invalidate the related tag after a write.
For a published crate, add HydraCache to an application:
cargo add hydracache
Inside this repository, the documentation examples use path dependencies so they are checked against the current branch.
let cache = HydraCache::local()
.default_ttl(Duration::from_secs(300))
.build();
let user_42_options = CacheOptions::new()
.ttl(Duration::from_secs(60))
.tag("users")
.tag("user:42");
cache
.put(
"user:42",
User {
id: 42,
name: "Ada".to_owned(),
},
user_42_options,
)
.await?;
let cached: Option<User> = cache.get("user:42").await?;
assert_eq!(cached.as_ref().map(|user| user.name.as_str()), Some("Ada"));
let loads = Arc::new(AtomicUsize::new(0));
let user_43_options = CacheOptions::new()
.ttl(Duration::from_secs(60))
.tag("users")
.tag("user:43");
let loaded = cache
.get_or_load("user:43", user_43_options, {
let loads = Arc::clone(&loads);
move || async move {
loads.fetch_add(1, Ordering::Relaxed);
Ok::<_, std::io::Error>(User {
id: 43,
name: "Grace".to_owned(),
})
}
})
.await?;
assert_eq!(loaded.name, "Grace");
assert_eq!(loads.load(Ordering::Relaxed), 1);
cache.invalidate_tag("user:42").await?;
assert_eq!(cache.get::<User>("user:42").await?, None);
The important parts are:
- values are typed at the cache boundary;
CacheOptionscarries TTL and invalidation metadata;- the loader runs only when the value is missing or expired;
- tag invalidation removes values related to a write;
- the example is compiled by the documentation examples crate.
Run the checked example from the repository root:
cargo run --manifest-path docs-site/examples/Cargo.toml --bin quick_start
Next, read Keys and Tags. Most HydraCache usage becomes straightforward once key identity and invalidation tags are clear.