项目作者: udoprog

项目描述 :
Futures-aware cache backed by sled
高级语言: Rust
项目地址: git://github.com/udoprog/futures-cache.git
创建时间: 2019-07-19T18:56:12Z
项目社区:https://github.com/udoprog/futures-cache

开源协议:Other

下载


futures-cache

github
crates.io
docs.rs
build status

Futures-aware cache abstraction.

Provides a cache for asynchronous operations that persist data on the
filesystem using sled. The async cache works by accepting a future, but
will cancel the accepted future in case the answer is already in the cache.

It requires unique cache keys that are serde serializable. To distinguish
across different sub-components of the cache, they can be namespaces using
Cache::namespaced.


State

The state of the library is:

  • API is limited to only wrap, which includes a timeout (#1).
  • Requests are currently racing in the wrap method, so multiple unecessary
    requests might occur when they should //! instead be queueing up (#2).
  • Entries only expire when the library is loaded (#3).
  • Only storage backend is sled (#4).


Usage

This library requires the user to add the following dependencies to use:

  1. futures-cache = "0.10.3"
  2. serde = {version = "1.0", features = ["derive"]}


Examples

Simple example showcasing fetching information on a github repository.

This is also available as an example you can run with:

  1. cargo run --example github -- --user udoprog --repo futures-cache
  1. use futures_cache::{Cache, Duration};
  2. use serde::Serialize;
  3. type Error = Box<dyn std::error::Error>;
  4. #[derive(Debug, Serialize)]
  5. enum GithubKey<'a> {
  6. Repo { user: &'a str, repo: &'a str },
  7. }
  8. async fn github_repo(user: &str, repo: &str) -> Result<String, Error> {
  9. use reqwest::header;
  10. use reqwest::{Client, Url};
  11. let client = Client::new();
  12. let url = Url::parse(&format!("https://api.github.com/repos/{}/{}", user, repo))?;
  13. let req = client
  14. .get(url)
  15. .header(header::USER_AGENT, "Reqwest/0.10")
  16. .build()?;
  17. let body = client.execute(req).await?.text().await?;
  18. Ok(body)
  19. }
  20. #[tokio::main]
  21. async fn main() -> Result<(), Error> {
  22. let db = sled::open("cache")?;
  23. let cache = Cache::load(db.open_tree("cache")?)?;
  24. let user = "udoprog";
  25. let repo = "futures-cache";
  26. let text = cache
  27. .wrap(
  28. GithubKey::Repo {
  29. user: user,
  30. repo: repo,
  31. },
  32. Duration::seconds(60),
  33. github_repo(user, repo),
  34. )
  35. .await?;
  36. println!("{}", text);
  37. Ok(())
  38. }