cached icon indicating copy to clipboard operation
cached copied to clipboard

Cache not refreshed.

Open lz1998 opened this issue 3 years ago • 4 comments

I use cached to check whether a key exist in the past 2 seconds, and I write an unit test, but it doesn't works.

#[cfg(test)]
mod tests {
    use std::thread::sleep;

    use cached::Cached;

    #[test]
    fn a() {
        let mut c = cached::TimedCache::with_lifespan_and_refresh(2, true);
        for i in 1..5 {
            let key = i.to_string().repeat(9999999);
            let value = true;
            c.cache_set(key, value);
            sleep(std::time::Duration::from_secs(1));
            // println!("{:?}", c.get_store());
        }
        assert!(c.cache_set(1.to_string().repeat(9999999), true).is_none());
    }
}

lz1998 avatar Jan 20 '22 17:01 lz1998

Yes, there does appear to be a bug. cache_set and cache_remove should be checking the timestamp of the existing value before returning. It looks like the TimedSized store has the same bug too. I'll put a fix in this evening.

https://github.com/jaemk/cached/blob/3a8d0e06c5f4098f3eb0e28c1e35a15738990e1f/src/stores/timed.rs#L177-L183 https://github.com/jaemk/cached/blob/3a8d0e06c5f4098f3eb0e28c1e35a15738990e1f/src/stores/timed_sized.rs#L167-L175

jaemk avatar Jan 20 '22 17:01 jaemk

In my application, the key will be a large string, so I hope to clear them as soon as possible to save memory.

lz1998 avatar Jan 20 '22 17:01 lz1998

The insert/remove bug is fixed by this commit https://github.com/jaemk/cached/commit/d5ac5fe27181e49078fa9e172a749609a0bd6514 and a new flush method was added to the timed and timed-sized caches in this commit https://github.com/jaemk/cached/commit/26ef57a749ae64db4c70f88ebf293836afd35b3d . cache_get will delete expired items when you try to access them, but if you want the cache to be constantly flushed, then you'll need to start your own background thread or task to call .flush() every couple seconds.

This was released in 0.30.0

jaemk avatar Jan 21 '22 00:01 jaemk

The insert/remove bug is fixed by this commit https://github.com/jaemk/cached/commit/d5ac5fe27181e49078fa9e172a749609a0bd6514 and a new flush method was added to the timed and timed-sized caches in this commit https://github.com/jaemk/cached/commit/26ef57a749ae64db4c70f88ebf293836afd35b3d . cache_get will delete expired items when you try to access them, but if you want the cache to be constantly flushed, then you'll need to start your own background thread or task to call .flush() every couple seconds.

This was released in 0.30.0

I have tried the latest version, and I found that metrics will not change when accessing items with cache_set.

lz1998 avatar Feb 04 '22 05:02 lz1998