Timeout structure in Go

huangapple go评论94阅读模式
英文:

Timeout structure in Go

问题

我正在寻找一种具有存储过期数据功能的存储方式。我的意思是,一种可以指定要存储的数据和超时时间的结构,该值在一段时间后会被删除。

英文:

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.

答案1

得分: 3

如果你需要用于缓存,可以考虑使用cache2go

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

cache2go是用于缓存的,它仅在内存中操作,但你可以指定一个数据加载程序来延迟加载给定键的缺失值。数据加载程序可以用于从磁盘加载值

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

go-cache也支持这一点,并支持从磁盘加载缓存项:

func (c *Cache) Set(k string, x interface{}, d time.Duration)
向缓存中添加一个项,替换任何现有项。如果持续时间为0,则使用缓存的默认过期时间。如果为-1,则该项永不过期。

func (c *Cache) Save(w io.Writer) error
将缓存的项(使用Gob)写入io.Writer。如果序列化失败,例如因为缓存中存在无法序列化的对象(如通道),则返回错误。

func (c *Cache) Load(r io.Reader) error
从io.Reader中添加(Gob序列化的)缓存项,排除当前缓存中已存在的任何项。

英文:

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.

huangapple
  • 本文由 发表于 2014年3月9日 20:29:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/22282176.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定