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

I would like to know are there any packages in golang that will have expiry and efficient

I checked a few, Here is one of them, But from the implementation perspective it is locking entire cache to write one entry (Check this) which is not needed right?

Is it possible to lock one entry instead of locking entire cache?

From the same repo you linked in your question, there is also an implementation of sharding strategy that should provide you with a lock per partition vs a lock for the whole cache. For example if you decide to partition using 4 caches, you can compute the modulo of some hash for the key and store in the cache at that index. Refining this same method, you could in theory shard using sub-partitions, decomposing the key thru a binary tree to give you the desired caching (and locking) granularity.

It is not easy to lock only one entry, but you wanna more efficient, a good practice in Go is to use channel to communicate with a sequential process. In this way, there is no shared variables and locks.

a simple example of this:

type request struct {
    reqtype string
    key      string
    val      interface{}
    response chan<- result 
}

type result struct {
    value interface{}
    err   error
}


type Cache struct{ requests chan request }

func New() *Cache {
    cache := &Cache{requests: make(chan request)}
    go cache.server()
    return cache
}

func (c *Cache) Get(key string) (interface{}, error) {
    response := make(chan result)
    c.requests <- request{key, response}
    res := <-response
    return res.value, res.err
}

func (c *Cache) Set(key, val string) {
    c.requests <- request{"SET", key, val, response}
}

func (c *Cache) server() {
    cache := make(map[string]interface{})
    for req := range memo.requests {
        switch req.reqtype {
            case "SET":
                cache[req.key] = req.val
            case "GET":
                e := cache[req.key]
                if e == nil {
                    req.response <- result{e, errors.New("not exist")}
                } else {
                    req.response <- result{e, nil}
                }
        }
    }
}