7次发布
| 0.0.8 | 2024年3月28日 |
|---|---|
| 0.0.7 | 2024年3月28日 |
#94 在 缓存
每月 88 次下载
9KB
147 代码行
zcache

Zcache是一个基于时间的内存缓存存储,旨在提供一个简单的API来缓存Rust应用程序的任何部分,而无需修改调用堆栈的其他部分。
用法
您可以缓存封装原始类型的 ZEntry 枚举变体
enum ZEntry {
Int(i64),
Float(f64),
Text(String),
Bool(bool),
}
ZCache 模块公开 fetch、read、write 和 clear 方法
fetch
fetch 接受缓存键的名称、可选的过期时间以及异步回调,用于在缓存缺失或过期时填充缓存
async fn get_ether_price() -> Result<f64> {
match ZCache::fetch("ether-price", Some(Duration::from_secs(60)), || async {
let price: f64 = json_client.get().await...
// logic to extract price from URL ...
Some(ZEntry::Float(price))
})
.await? {
ZEntry::Float(price) => Ok(price),
_ => panic!("Unexpected type!"),
}
}
在上面的实现中,get_ether_price 返回从URL获取的价格。它仅在每60秒触发一次HTTP请求。
一个限制是,异步回调不能返回 Err,因此您必须通过返回 None 来通过缓存刷新来传达失败。
read 和 write
async fn refresh_ether_price() -> Result<()> {
let price: f64 = json_client.get().await...
let price = ZEntry::Float(price);
ZCache::write("ether-price", price, Some(Duration::from_secs(60)))
Ok(())
}
fn get_ether_price() -> Some(f64) {
ZCache::read("ether-price", price)
}
在上面的示例中,异步函数 write 可以定期刷新从URL获取的价格。与 fetch 相比,read 的优点是它不是 async,因此可以在您的应用程序的非异步部分中使用它。
clear
ZCache::clear();
使用它来删除所有缓存条目。
状态
所有这些方法都只是 unsafe 可变静态变量的花哨包装,因此请谨慎操作。在多线程环境中预计会发生数据竞争。但是,由于我仅将其用于缓存,因此我认为这是可以接受的。
我在生产应用程序中使用了 zcache,但请将其视为概念验证。我的Rust经验有限,因此欢迎反馈。
依赖关系
~0.3–0.8MB
~19K SLoC