2个版本
0.1.1 | 2020年3月10日 |
---|---|
0.1.0 | 2020年3月9日 |
#220 in 缓存
37KB
669 行
ABA Cache
为了减少频繁访问/计算成本高昂的操作而编写的简单缓存(目前仅作为实验性使用,尚未用于生产)
此实现基于"LRU Cache",另一个灵感来自"在Rust中编写双向链表很简单"。
示例
基本LRU缓存
将以下依赖项添加到Cargo.toml
[dependencies]
aba-cache = { version = "0.1.0", default-features = false }
在main.rs上
use aba_cache as cache;
fn main() {
// create Cache, with multiple_cap set to 2
// and entry will be timeout after 10 seconds
let mut cache = cache::LruCache::<usize, &str>::new(2, 10);
cache.put(1, "a");
cache.put(2, "b");
cache.put(2, "c");
cache.put(3, "d");
assert_eq!(cache.get(&1), Some(&"a"));
assert_eq!(cache.get(&2), Some(&"c"));
assert_eq!(cache.get(&3), Some(&"d"));
}
异步LRU缓存
将以下依赖项添加到Cargo.toml
[dependencies]
aba-cache = { version = "0.1.0" }
tokio = { version = "0.2", features = ["macros", "rt-core"] }
在main.rs上
use aba_cache as cache;
#[tokio::main]
async fn main() {
// create Cache, with multiple_cap set to 2
// and entry will be timeout after 10 seconds
// additionally, this setup runtime daemon to evict outdate entry
// every 10 seconds
let cache = cache::LruAsyncCache::<usize, &str>::new(2, 10);
cache.put(1, "a").await;
cache.put(2, "b").await;
cache.put(2, "c").await;
cache.put(3, "d").await;
assert_eq!(cache.get(&1).await, Some("a"));
assert_eq!(cache.get(&2).await, Some("c"));
assert_eq!(cache.get(&3).await, Some("d"));
}
参考
依赖项
~0–0.9MB
~12K SLoC