It it possible to serialize cache data? #235
-
Hi! This might be a weird use-case, but is it possible to extract cache data, or create a cache from a hashmap and vice versa? When my application starts, I would like to pull of some data from Redis, to cache in memory. On shutdown I want to dump the data back to Redis so it isn't lost. This is simple enough with a
And use, e.g., Is there a way for me to perform and equivalent operation to the one described here, but with the moka cache? 🙇 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Hi.
There is a limitation though. I will explain it later. Exampleuse std::collections::HashMap;
use moka::sync::Cache;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
struct ResultItem {
value: String,
}
fn main() {
// Create a cache.
let cache = Cache::builder().max_capacity(1024).build();
// Insert a value for "key1".
cache.insert(
"key1".to_string(),
ResultItem {
value: "value1".to_string(),
},
);
// Get the value for "key1".
dbg!(cache.get("key1"));
// Copy all entries to a HashMap.
let all_entries: HashMap<_, _> = cache
.iter()
.map(|(k, v)| {
// k: Arc<String>, v: ResultItem
// Convert k to String by cloning it.
(k.as_ref().clone(), v)
})
.collect();
// Serialize the HashMap using serde + bincode.
let serialized = bincode::serialize(&all_entries).unwrap();
// Create another cache.
let cache = Cache::builder().max_capacity(1024).build();
// Deserialize the HashMap and insert all entries into the cache.
let all_entries: HashMap<String, ResultItem> = bincode::deserialize(&serialized).unwrap();
for (k, v) in all_entries {
cache.insert(k, v);
}
// Get the value for "key1".
dbg!(cache.get("key1"));
} Limitation
|
Beta Was this translation helpful? Give feedback.
Hi.
moka
cache currently do not provide a convenient way to serialize the cache data. So you need to do it by yourself:std::collections::HashMap
.HashMap
into binary usingserde
andbincode
.There is a limitation though. I will explain it later.
Example