#cache #expiration #time #set #in-memory #delete #fruit

pocketcache

一个简单的 Rust 内存缓存

1 个不稳定版本

0.0.1 2020 年 9 月 10 日

#4#fruit

MIT 许可证

10KB
132

pocketcache

Crates.io Test

一个简单的 Rust 内存缓存。

安装

[dependencies]
pocketcache = "0.0.1"

使用方法

use pocketcache::cache::Cache;
use pocketcache::time::Expiration;

#[derive(Debug)]
struct Data {
  messages: Vec<String>,
}

fn main() {
  let expiration = Expiration::Hour(3);
  let mut cache = Cache::<Data>::new(expiration);

  // set
  cache.set(
    "fruit",
    Data {
      messages: vec![String::from("peach")],
    },
  );

  // get
  let fruit = cache.get("fruit");
  println!("{:#?}", fruit); // Some( Data { messages: { ["peach"] } } )

  // delete
  cache.delete("fruit");
  let fruit = cache.get("fruit");
  println!("{:#?}", fruit); // None
}

API

过期时间

use pocketcache::time::Expiration;

let expiration = Expiration::Second(30); // 30ces
let expiration = Expiration::Minute(5); // 5min
let expiration = Expiration::Hour(3); // 3 hour
let expiration = Expiration::Default; // 1 hour

缓存

use pocketcache::cache::Cache;
use pocketcache::time::Expiration;

let mut cache = Cache::<&str>::new(Expiration::Default);

设置

cache.set("fruit", "banana");
cache.set("vegetable", "carrot");
cache.set("meat", "crab");

获取

let mut cache = Cache::<&str>::new(Expiration::Default);

let fruit = cache.get("fruit");
println!("{:#?}", fruit); // None

cache.set("fruit", "banana");
let fruit = cache.get("fruit");
println!("{:#?}", fruit); // Some("banana")

cache.set("fruit", "peach");
let fruit = cache.get("fruit");
println!("{:#?}", fruit); // Some("peach")

// after 1 hour...

let fruit = cache.get("fruit");
println!("{:#?}", fruit); // None

删除

cache.set("fruit", "banana");
cache.delete("fruit");

let fruit = cache.get("fruit");
println!("{:#?}", fruit); // None

清除

cache.set("fruit", "banana");
cache.set("vegetable", "carrot");
cache.set("meat", "crab");
cache.clear();

println!("{:#?}", cache.get("fruit")); // None
println!("{:#?}", cache.get("vegetable")); // None
println!("{:#?}", cache.get("meat")); // None

无运行时依赖