#cache #tags #i32 #invalidation #back-end #applications #async-cache

fnct

Simple caching library that supports cache invalidation via tags

12 releases

0.6.5 Jul 29, 2024
0.6.3 Mar 11, 2024
0.6.2 Dec 6, 2023
0.6.1 Sep 20, 2023
0.2.0 Mar 22, 2023

#340 in Caching

Download history 28/week @ 2024-07-22 343/week @ 2024-07-29 18/week @ 2024-08-05 46/week @ 2024-08-12 20/week @ 2024-08-19 13/week @ 2024-08-26 33/week @ 2024-09-02 64/week @ 2024-09-09 21/week @ 2024-09-16 15/week @ 2024-09-23 2/week @ 2024-09-30 15/week @ 2024-10-14 2/week @ 2024-10-21 28/week @ 2024-10-28 32/week @ 2024-11-04

77 downloads per month

MIT license

27KB
383 lines

check test codecov Version dependency status

fnct

Simple caching library for Rust that supports cache invalidation via tags

Example

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
}

Dependencies

~7–16MB
~208K SLoC