doujian0265 2016-10-28 09:37
浏览 89
已采纳

Golang:在LRU缓存中存储地图结构的正确方法

I have a structure like: map[key]value, and I want to store it in "github.com/golang/groupcache/lru" by a string key, say, the cacheKey.

Here is my question:

I found whenever I want update the cached item, I need to Get it first:

item := cache.Get(cacheKey)
if v, ok := item[key]; ok{
    item[key]=new_value
    cache.Add(cacheKey, item)
}

Is it right way to do this?

Or, as some of people suggested, I need to re-design my structure to make sure I can do cache.Add(cacheKey, item) whenever I want to update it.

Or, I should even use a combined key like cacheKey_key to store that item?

  • 写回答

1条回答 默认 最新

  • doumei1203 2016-11-05 00:55
    关注

    The code above will work. I looked at the source of LRU cache you refer to. Here are my notes:

    • whatever you decide, make sure access to this LRU is thread-safe if you plan to use it within goroutines.
    • you may store *map instead of plain map, which would eliminate a need to call add.
    • if it's ok to add to the map with override, skip presence check (if v, ok...)

    So having said that, here is what it becomes:

    m sync.Mutex
    m.Lock()
    defer m.Unlock()
    cache.Get(cacheKey)[key] = new_value
    

    If you elaborate on what sort of data you are planning to store, we may try to come up with an alternative solution.

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

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大