Expand description
§unistore-cache
内存缓存能力 - UniStore 能力生态的一部分。
§功能特性
- LRU 淘汰: 基于最近最少使用策略自动淘汰
- TTL 支持: 可设置条目过期时间
- 线程安全: 使用 parking_lot 高性能锁
- 统计信息: 命中率、大小等缓存统计
- 泛型支持: 支持任意 Key-Value 类型
§快速开始
use unistore_cache::{Cache, CacheConfig};
use std::time::Duration;
// 创建缓存
let cache: Cache<String, String> = Cache::new(CacheConfig::default()
.max_capacity(1000)
.default_ttl(Duration::from_secs(300)));
// 存取数据
cache.insert("key1".to_string(), "value1".to_string());
let value = cache.get(&"key1".to_string());
assert_eq!(value, Some("value1".to_string()));§自定义 TTL
use unistore_cache::{Cache, CacheConfig};
use std::time::Duration;
let cache: Cache<&str, i32> = Cache::with_defaults();
// 使用默认 TTL
cache.insert("key1", 100);
// 使用自定义 TTL
cache.insert_with_ttl("key2", 200, Some(Duration::from_secs(60)));
// 永不过期
cache.insert_with_ttl("key3", 300, None);§Get or Insert
use unistore_cache::Cache;
let cache: Cache<&str, String> = Cache::with_defaults();
// 如果不存在则计算并插入
let value = cache.get_or_insert_with("expensive_key", || {
// 昂贵的计算...
"computed_value".to_string()
});§统计信息
use unistore_cache::Cache;
let cache: Cache<&str, i32> = Cache::with_defaults();
cache.insert("key1", 42);
cache.get(&"key1");
cache.get(&"key2"); // miss
let stats = cache.stats();
println!("命中率: {:.2}%", stats.hit_rate() * 100.0);Structs§
- Cache
- LRU 缓存
- Cache
Config - 缓存配置
- Cache
Entry - 缓存条目
- Cache
Stats - 缓存统计
- Cache
Stats Snapshot - 统计快照(不可变)
Enums§
- Cache
Error - 缓存错误