Crate fnct

Source
Expand description

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
}

Re-exports§

pub use postcard;
pub use serde;
pub use serde_json;serde_json

Modules§

backend
Backends are used to communicate with the cache and implement the most basic low level functions like get and put.
format
Formatters are used to serialize and deserialize data for storing it in a cache.

Macros§

key
Create a cache key that includes the source location where the macro was invoked and the crate name and version.
keyfn
Create a function that generates a cache key using the key! macro. Useful if you need shared access to the same cache key.

Structs§

AsyncCache
A cache that can be used asynchronously.

Enums§

Error