golang中如何实现高效的内存键值存储

我想知道 golang 中是否有任何会过期且有效的包

我查了一些,这是一个他们,但是从实现的角度来看它是锁定整个缓存写入一个条目(检查这是不对的需要)?

是否可以锁定一个条目而不是锁定整个缓存?


GCT1015
浏览 182回答 2
2回答

子衿沉夜

从您在问题中链接的同一个 repo 中,还有一个分片策略的实现,它应该为您提供每个分区的锁而不是整个缓存的锁。例如,如果您决定使用 4 个缓存进行分区,则可以计算该键的某个散列的模数并存储在该索引的缓存中。改进相同的方法,理论上您可以使用子分区进行分片,通过二叉树分解键,为您提供所需的缓存(和锁定)粒度。

哆啦的时光机

只锁定一个条目并不容易,但是您想要更高效,Go 中的一个好做法是使用通道与顺序进程进行通信。这样,就没有共享变量和锁了。一个简单的例子:type request struct {&nbsp; &nbsp; reqtype string&nbsp; &nbsp; key&nbsp; &nbsp; &nbsp; string&nbsp; &nbsp; val&nbsp; &nbsp; &nbsp; interface{}&nbsp; &nbsp; response chan<- result&nbsp;}type result struct {&nbsp; &nbsp; value interface{}&nbsp; &nbsp; err&nbsp; &nbsp;error}type Cache struct{ requests chan request }func New() *Cache {&nbsp; &nbsp; cache := &Cache{requests: make(chan request)}&nbsp; &nbsp; go cache.server()&nbsp; &nbsp; return cache}func (c *Cache) Get(key string) (interface{}, error) {&nbsp; &nbsp; response := make(chan result)&nbsp; &nbsp; c.requests <- request{key, response}&nbsp; &nbsp; res := <-response&nbsp; &nbsp; return res.value, res.err}func (c *Cache) Set(key, val string) {&nbsp; &nbsp; c.requests <- request{"SET", key, val, response}}func (c *Cache) server() {&nbsp; &nbsp; cache := make(map[string]interface{})&nbsp; &nbsp; for req := range memo.requests {&nbsp; &nbsp; &nbsp; &nbsp; switch req.reqtype {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case "SET":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cache[req.key] = req.val&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case "GET":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e := cache[req.key]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if e == nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; req.response <- result{e, errors.New("not exist")}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; req.response <- result{e, nil}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go