Async Cache Library
This library provides an async cache implementation that can be used to store and retrieve data with an expiration time. It can store data in memory and can asynchronously fetch data using a custom data fetcher.
API Overview
;
;
Guide
To use AsyncCache, you need to implement the Fetcher trait for the type you want to cache. Then you can use the AsyncCacheBuilder struct to configure the cache and create an instance of AsyncCache.
Create an instance of AsyncCache using the AsyncCacheBuilder struct.
let builder = builder;
let cache = builder.build;
Then, you can interact with the cache by using its methods: set_default, get, get_or_set, and delete.
set_default
Here's an example of how to set a default value for a key:
cache.set_default;
This sets the default value for the key "key" to "default_value".
get
Getting a value from the cache is done asynchronously using the get method. It returns an Option<T> where T is the type of the value in the cache. If the key was not found, it will try to fetch it, and if the first fetch fails, it returns None.
let value = cache.get.await.unwrap;
This gets the value for the key "key" from the cache.
get_or_set
If you want to set a value for a key if it's not found in the cache, you can use the get_or_set method:
let value = cache.get_or_set;
This gets the value for the key "key" from the cache. If the value was not found, it sets it to "default_value". Either way, it returns the value of the key.
delete
If you want to delete data from the cache, you can use the delete method.
cache.delete.await;
This deletes all keys that start with the prefix "prefix_" from the cache.
Builder
The AsyncCacheBuilder struct is used to configure the AsyncCache. It takes in the Fetcher trait, the refresh interval, and an optional expire interval. You can also pass in mpsc channels to receive errors, changes to values, or deletions.
let builder = builder
.with_expire
.with_error_tx
.with_delete_tx;
with_expire sets the expire interval for the cache. If this is not set, the default expire interval is 180 seconds.
with_error_tx sets the mpsc channel for receiving errors.
with_delete_tx sets the broadcast channel for receiving deletions.
License
The async cache library is licensed under MIT OR Apache-2.0.