go-cache icon indicating copy to clipboard operation
go-cache copied to clipboard

Get Expired Item

Open FinweVI opened this issue 6 years ago • 2 comments

It could be nice to be able to retrieve Items that are in cache but already expired. I have an expiration time set at 5min and a cleanup time set at 24h.

I'm querying a remote API and I want to be able to use my expired Item if the remote API is not answering to keep my service running.

I've been playing with something like this (the last arg is the one defining if the object is expired):

func (c *cache) GetEvenIfExpired(k string) (interface{}, time.Time, bool) {
    c.mu.RLock()
    // "Inlining" of get and Expired
    item, found := c.items[k]
    if !found {
        c.mu.RUnlock()
        return nil, time.Time{}, true
    }

    if item.Expiration > 0 {
        if time.Now().UnixNano() > item.Expiration {
            c.mu.RUnlock()
            return item.Object, time.Unix(0, item.Expiration), true
        }

        // Return the item and the expiration time
        c.mu.RUnlock()
        return item.Object, time.Unix(0, item.Expiration), false
    }

    // If expiration <= 0 (i.e. no expiration time set) then return the item
    // and a zeroed time.Time
    c.mu.RUnlock()
    return item.Object, time.Time{}, false
}

This allow me to renew my cache if the object is expired and the remote API is answering, or use my cache if anything wrong is happening.

FinweVI avatar Jun 26 '19 17:06 FinweVI

Great idea. We have this exact use case as well

romandvoskin avatar Oct 03 '19 18:10 romandvoskin

Old topic, and repo seems to be dead, but if anybody will looks for this again, can use my fork with added such functionality - here is PR: #63

oskarwojciski avatar Oct 11 '20 19:10 oskarwojciski