duanqiao1961 2014-03-09 12:29
浏览 24
已采纳

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条回答 默认 最新

  • dongwei8440 2014-03-09 13:27
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)