Skip to main content

Module cache

Module cache 

Source
Expand description

A key-value cache for expensive results.

let menu: Vec<Product> = state.cache.remember("menu", Duration::from_secs(600), || async {
    Product::query().order_by("name").get(&state.db).await
}).await?;
state.cache.forget("menu").await?;   // after the menu changes

Counters, one-time values and locks:

let views = state.cache.increment("views:home", 1).await?; // atomic; 1 the first time
if state.cache.add("welcome-sent:7", &true, Some(Duration::from_secs(86_400))).await? {
    // only the first caller gets here
}
let code: Option<String> = state.cache.pull("otp:7").await?; // read once, then gone

// One process at a time handles this order; others wait up to 5 s.
let lock = state.cache.lock(&format!("order:{order_id}"), Duration::from_secs(30));
let guard = lock.block(Duration::from_secs(5)).await?;
// ... work on the order ...
guard.release().await?; // or let it drop

CACHE_STORE=memory (default) keeps values in this process; database keeps them in the cache table, so they survive restarts and are shared with queue:work processes and other servers (locks included). Values are stored as JSON. Keys starting with renox: belong to the framework (e.g. scheduler claims, locks). Expired rows of the database store are deleted now and then as values are written, and by my-app cache:prune.

Structs§

Cache
The app’s cache (state.cache), in memory or the cache table (CACHE_STORE).
Lock
A named lock from Cache::lock.
LockGuard
A held Lock. Released by LockGuard::release, when dropped (in the background), or when its ttl runs out.