This directory contains examples of how to use Moka cache. Each example is a standalone binary that can be run with the following command:
$ cargo run --example <example_name> -F sync,future
Each example has a suffix _async
or _sync
:
_async
indicates that the example uses themoka::future::Cache
, which is aFuture
-aware, concurrent cache._sync
indicates that the example uses themoka::sync::Cache
, which is a multi-thread safe, concurrent cache.
-
- Shares a cache between async tasks or OS threads.
- Do not wrap a
Cache
withArc<Mutex<_>>
! Just clone theCache
and you are all set.
- Do not wrap a
- Uses
insert
,get
andinvalidate
methods.
- Shares a cache between async tasks or OS threads.
-
- Configures the max capacity of the cache based on the total size of the cached entries.
Atomically inserts, updates and removes an entry from the cache depending on the existence of the entry.
- counter_async and counter_sync
- Atomically increments a cached
u64
by 1. If the entry does not exist, inserts a new entry with the value 1. - Uses
and_upsert_with
method.
- Atomically increments a cached
- bounded_counter_async and
bounded_counter_sync
- Same as above except removing the entry when the value is 2.
and_compute_with
method.
- append_value_async and
append_value_sync
- Atomically appends an
i32
to a cachedArc<RwLock<Vec<i32>>>
. If the entry does not exist, inserts a new entry. - Uses
and_upsert_with
method.
- Atomically appends an
- try_append_value_async and
try_append_value_sync
- Atomically reads an
char
from a reader and appends it to a cachedArc<RwLock<String>>
, but reading may fail by an early EOF. - Uses
and_try_compute_with
method.
- Atomically reads an
-
- Configures the
time_to_live
expiration policy. - Registers a listener (closure) to be notified when an entry is evicted from the cache.
- Uses
insert
,invalidate
,invalidate_all
andrun_pending_tasks
methods. - Demonstrates when the expired entries will be actually evicted from the cache,
and why the
run_pending_tasks
method could be important in some cases.
- Configures the
-
- Controls the lifetime of the objects in a separate
BTreeMap
collection from the cache using an eviction listener. - Beside the cache APIs, uses
BTreeMap
,Arc
and mpsc channel (multi-producer, single consumer channel).
- Controls the lifetime of the objects in a separate
-
- Reinserts the expired entries into the cache using eviction listener and worker threads.
- Spawns two worker threads; one for reinserting entries, and the other for
calling
run_pending_tasks
. - Uses a mpsc channel (multi-producer, single consumer channel) to send commands from the eviction listener to the first worker thread.
The examples are not meant to be exhaustive. Please check the API documentation for more examples and details.