#cache #async #future #sled #futures-aware #operations #backed

futures-cache

由 sled 支持的 futures-aware 缓存

14 个版本 (9 个破坏性更新)

0.10.3 2023年3月22日
0.10.1 2023年1月2日
0.10.0 2020年12月29日
0.9.0 2019年12月30日
0.6.0 2019年7月27日

#1046 in 异步

Download history 34/week @ 2024-04-13 6/week @ 2024-05-18 11/week @ 2024-05-25 7/week @ 2024-06-01 22/week @ 2024-06-08 29/week @ 2024-06-15 11/week @ 2024-06-22 12/week @ 2024-06-29 29/week @ 2024-07-20 41/week @ 2024-07-27

每月 82 次下载

MIT/Apache

36KB
600 代码行

futures-cache

github crates.io docs.rs build status

Futures-aware 缓存抽象。

为使用 sled 在文件系统中持久化数据异步操作提供缓存。异步缓存通过接受一个 future 来工作,但如果答案已经在缓存中,则会取消已接受的 future。

它需要唯一的可序列化缓存键,可以使用 Cache::namespaced 方法区分不同的缓存子组件。


状态

库的状态是

  • API 仅限于 wrap,它包括超时 (#1)。
  • 当前在 wrap 方法中请求正在竞态,因此当它们应该排队时,可能会发生多个不必要的请求 (#2)。
  • 条目仅在库加载时过期 (#3)。
  • 仅支持 sled 存储后端 (#4)。

使用方法

此库需要用户添加以下依赖项才能使用

futures-cache = "0.10.2"
serde = {version = "1.0", features = ["derive"]}

示例

简单示例展示了获取 GitHub 存储库信息的过程。

这也可以作为一个可以运行的示例,您可以使用

cargo run --example github -- --user udoprog --repo futures-cache
use futures_cache::{Cache, Duration};
use serde::Serialize;

type Error = Box<dyn std::error::Error>;

#[derive(Debug, Serialize)]
enum GithubKey<'a> {
    Repo { user: &'a str, repo: &'a str },
}

async fn github_repo(user: &str, repo: &str) -> Result<String, Error> {
    use reqwest::header;
    use reqwest::{Client, Url};

    let client = Client::new();

    let url = Url::parse(&format!("https://api.github.com/repos/{}/{}", user, repo))?;

    let req = client
        .get(url)
        .header(header::USER_AGENT, "Reqwest/0.10")
        .build()?;

    let body = client.execute(req).await?.text().await?;
    Ok(body)
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    let db = sled::open("cache")?;
    let cache = Cache::load(db.open_tree("cache")?)?;

    let user = "udoprog";
    let repo = "futures-cache";

    let text = cache
        .wrap(
            GithubKey::Repo {
                user: user,
                repo: repo,
            },
            Duration::seconds(60),
            github_repo(user, repo),
        )
        .await?;

    println!("{}", text);
    Ok(())
}

依赖项

~5–11MB
~112K SLoC