Cache
10/30/24Less than 1 minute
Cache
The caching system provides a unified interface supporting both Redis and in-memory backends.
Quick Start
1) Initialize at Startup
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Load APPCOFIG first
// Initialize global cache
CacheManager::init().await?;
Ok(())
}2) Use in Business Code
#[derive(serde::Serialize, serde::Deserialize, Clone)]
pub struct User {
pub id: i64,
pub name: String,
}
async fn get_user(id: i64) -> anyhow::Result<User> {
let cache = CacheManager::instance().await;
let key = format!("user:{id}");
if cache.contains_key(&key).await {
if let Ok(u) = cache.get_value::<User>(&key).await {
return Ok(u);
}
}
let u = load_user_from_db(id).await?;
let _ = cache.set_value_ex(&key, &u, 3600).await;
Ok(u)
}Core Capabilities
1) String KV
set_string,get_string,set_string_ex(with TTL)
2) Structured Objects (JSON serialization)
set_value,get_value,set_value_ex— auto (de)serialization
3) Namespace & Direct Access
- Default namespace prefix; use
directmethods for raw keys
4) List Queues & Blocking Consumption
lpush,rpop,brpopfor task queues
5) Sets & Idempotency
sadd,sismemberfor deduplication
6) Sorted Sets & Delayed Tasks
zadd,zrangebyscorefor delayed job scheduling
7) Distributed Locks & Atomic Writes
set_lock,release_lockfor distributed coordination
8) Full/Page Search (Ops)
keys,scanfor maintenance
Configuration
[cache]
cache_type = "redis" # redis or memory
namespace = "qiluo"
pool_size = 12
url = "redis://127.0.0.1/"
# For memory mode:
# pool_size = 100000Best Practices
- Prefer cache-aside pattern (load from DB on miss, then cache)
- Use TTL for all cached data to avoid stale data
- Use
get_one_usefor OTP-style one-time reads