Question

I'm looking for a storage with the ability of storing expiring data. I mean, a structure where you could specify the data to be stored and a timeout, and where that value would be removed after some time.

Was it helpful?

Solution

If you need this for caching, consider using cache2go:

cache := cache2go.Cache("c")
val := struct{x string}{"This is a test!"}
cache.Add("valA", 5*time.Second, &val)

As cache2go is for caching it operates on memory alone but you can specify a data loading routine to lazily load a missing value for a given key. The data loader can be utilized to load the value from disk:

cache.SetDataLoader(func(key interface{}) *cache2go.CacheItem {
    val := loadFromDisk()
    item := cache2go.CreateCacheItem(key, 0, val)
    return &item
})

go-cache supports this as well and supports loading cached items from disk:

func (c *Cache) Set(k string, x interface{}, d time.Duration)
Adds an item to the cache, replacing any existing item. If the duration is 0, the cache's default expiration time is used. If it is -1, the item never expires.

func (c *Cache) Save(w io.Writer) error
Writes the cache's items (using Gob) to an io.Writer. Returns an error if the serialization fails, e.g. because there are unserializable objects like channels in the cache.

func (c *Cache) Load(r io.Reader) error
Adds (Gob-serialized) cache items from an io.Reader, excluding any items that already exist in the current cache.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top