jaemk / cached

Rust cache structures and easy function memoization

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

let cache = &#cache_ident;
(or here for async)
let cache = &#cache_ident.get().await;

For example, we could add the following lines to the redis example (

cached/examples/redis.rs

Lines 80 to 87 in 8cd2f39

print!("1. first sync call with a 2 seconds sleep...");
io::stdout().flush().unwrap();
cached_sleep_secs(2).unwrap();
println!("done");
print!("second sync call with a 2 seconds sleep (it should be fast)...");
io::stdout().flush().unwrap();
cached_sleep_secs(2).unwrap();
println!("done");
)

     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.