https://github.com/defelo/fnct
Simple caching library for Rust that supports cache invalidation via tags
https://github.com/defelo/fnct
Last synced: 3 months ago
JSON representation
Simple caching library for Rust that supports cache invalidation via tags
- Host: GitHub
- URL: https://github.com/defelo/fnct
- Owner: Defelo
- License: mit
- Created: 2023-03-21T12:39:56.000Z (about 2 years ago)
- Default Branch: develop
- Last Pushed: 2024-11-15T07:57:55.000Z (6 months ago)
- Last Synced: 2025-01-31T13:11:11.189Z (4 months ago)
- Language: Rust
- Homepage: https://docs.rs/fnct
- Size: 80.1 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://github.com/Defelo/fnct/actions/workflows/check.yml)
[](https://github.com/Defelo/fnct/actions/workflows/test.yml)
[](https://codecov.io/gh/Defelo/fnct)

[](https://deps.rs/repo/github/Defelo/fnct)# fnct
Simple caching library for Rust that supports cache invalidation via tags## Example
```rust
use std::time::Duration;use fnct::{backend::AsyncRedisBackend, format::PostcardFormatter, keyfn, AsyncCache};
use redis::{aio::MultiplexedConnection, Client};struct Application {
cache: AsyncCache, 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
}
```