1 个不稳定版本
0.1.0 | 2023 年 4 月 17 日 |
---|
#24 in #stored
12KB
120 行
Artifacts Crate
一个用于管理存储在 JSON 文件中的数据共享读写访问的 crate。`Artifact` 结构体支持从 JSON 文件初始化数据,获取数据的读锁,更新数据,并监视文件变化,以自动在指定间隔重新加载数据。
用法
- 将以下内容添加到您的
Cargo.toml
文件中
[dependencies]
artifacts-crate = "0.1.0"
- 定义您的结构体并确保它实现了 DeserializeOwned
#[derive(Deserialize, Debug)]
struct ExampleStruct {
field1: String,
field2: u32,
}
- 使用您的结构体初始化 Artifact
pub static EXAMPLE_LIST: Artifact<ExampleStruct> = Artifact::new();
- 在主函数或其他适当的位置,初始化 Artifact 数据并启动监视任务
#[tokio::main]
async fn main() {
// Initialize the EXAMPLE_LIST data
EXAMPLE_LIST.init("example.json").await.unwrap();
// Spawn a background task to watch and reload the EXAMPLE_LIST data every 6 hours
tokio::spawn(EXAMPLE_LIST.watch("example.json".to_string(), 6 * 60 * 60));
// Example of getting the data
{
let example_data = EXAMPLE_LIST.get().await.unwrap();
println!("Example data: {:?}", *example_data);
}
// Example of updating the data
{
let new_data = ExampleStruct { field1: "New field1 value".to_string(), field2: 42 };
EXAMPLE_LIST.update(new_data).await.unwrap();
}
}
有关更多详细信息,请参阅 crate 文档或阅读源代码中的注释。
许可证
本项目采用 MIT 许可证。
依赖项
~3–10MB
~95K SLoC