How to remove a key with a cached fn using Redis proc macro
jqnatividad opened this issue · comments
In other cached fns, you can do something like this:
cached!{
COMPUTE: SizedCache<(u64, u64), u64> = SizedCache::with_size(50);
fn compute(a: u64, b: u64) -> u64 = {
sleep(Duration::new(2, 0));
return a * b;
}
}
let cache = COMPUTE.lock().unwrap();
cache.cache_remove(&42);
However, with a cached fn using a Redis proc macro, I can't do this.
What is the equivalent of acquiring a lock on the global static for the Redis proc macro?
Hi @jqnatividad! There is a global static created when using the #[io_cached]
proc macro, the same way one is created when using the #[cached]
proc macro. However, the global static created by the #[io_cached]
macro is not synchronized, since the synchronization is happening somewhere else (over “io”). You can see that the io-cached trait methods only require &self
- here’s the cache-remove method https://docs.rs/cached/latest/cached/stores/struct.RedisCache.html#method.cache_remove.
So that means you can call methods directly on the global reference, like what the macro expands to here
cached/cached_proc_macro/src/lib.rs
Line 1493 in 8cd2f39
cached/cached_proc_macro/src/lib.rs
Line 1465 in 8cd2f39
For example, we could add the following lines to the redis example (
Lines 80 to 87 in 8cd2f39
use cached::IOCached;
CACHED_SLEEP_SECS.cache_remove(&2).unwrap();
print!("third sync call with a 2 seconds sleep (slow, after cache-remove)...");
io::stdout().flush().unwrap();
cached_sleep_secs(2).unwrap();
println!("done");
Thanks @jaemk that worked!
And yeah, it'd be great if you add that snippet to the redis example.