12 个版本

0.6.5 2024年7月29日
0.6.3 2024年3月11日
0.6.2 2023年12月6日
0.6.1 2023年9月20日
0.2.0 2023年3月22日

#298 in 缓存

Download history 26/week @ 2024-04-26 18/week @ 2024-05-03 11/week @ 2024-05-10 17/week @ 2024-05-17 13/week @ 2024-05-24 12/week @ 2024-05-31 23/week @ 2024-06-07 21/week @ 2024-06-14 17/week @ 2024-06-21 9/week @ 2024-06-28 9/week @ 2024-07-05 17/week @ 2024-07-12 30/week @ 2024-07-19 318/week @ 2024-07-26 45/week @ 2024-08-02 35/week @ 2024-08-09

每月 432 次下载

MIT 许可证

27KB
383

check test codecov Version dependency status

fnct

支持通过标签进行缓存失效的简单 Rust 缓存库

示例

use std::time::Duration;

use fnct::{backend::AsyncRedisBackend, format::PostcardFormatter, keyfn, AsyncCache};
use redis::{aio::MultiplexedConnection, Client};

struct Application {
    cache: AsyncCache<AsyncRedisBackend<MultiplexedConnection>, PostcardFormatter>,
}

keyfn!(my_cache_key(a: i32, b: i32));
impl Application {
    async fn test(&self, a: i32, b: i32) -> i32 {
        self.cache
            .cached(my_cache_key(a, b), &["sum"], None, || async {
                // expensive computation
                a + b
            })
            .await
            .unwrap()
    }
}

#[tokio::main]
async fn main() {
    let Ok(redis_server) = std::env::var("REDIS_SERVER") else { return; };
    let client = Client::open(redis_server).unwrap();
    let conn = client.get_multiplexed_async_connection().await.unwrap();
    let app = Application {
        cache: AsyncCache::new(
            AsyncRedisBackend::new(conn, "my_application".to_owned()),
            PostcardFormatter,
            Duration::from_secs(600),
        ),
    };
    assert_eq!(app.test(1, 2).await, 3); // run expensive computation and fill cache
    assert_eq!(app.test(1, 2).await, 3); // load result from cache
    app.cache.pop_key(my_cache_key(1, 2)).await.unwrap(); // invalidate cache by key
    app.cache.pop_tag("sum").await.unwrap(); // invalidate cache by tag
}

依赖项

~6–16MB
~226K SLoC