golang的一个基于内存的key-value 缓存

时间:2025-03-08 07:12:28

前两天业务里边需要一个需求需要用到一个带有时效性的单机缓存,对于数据不要求固化存储,于是乎就自己写了一个简单的key-value的memcache。

整个cache提供了,set、get、replace,delete等方法,在初始化cache的时候可以根据业务需求初始化每个item在cache中的失效时间,以及检测删除过期数据的时间周期。提供了一个对int型value计数的方法Increment。

缓存源码的链接,也可以通过 go get /UncleBig/goCache 的方式获取。 下面

下面是一个使用的例子,对每个方法都有简要的说明

package example

import (
    cache "UncleBig/goCache"
    "fmt"
    "time"
)

func main() {
    // Create a cache with a default expiration time of 5 minutes, and which
    // purges expired items every 30 seconds
    c := (10*time.Minute, 30*time.Second)

    // Set the value of the key "foo" to "bar", with the default expiration time
    c.Set("foo", "bar", )

    // Get the string associated with the key "foo" from the cache
    //foo, found := c.Get("foo")
    if foo, found := c.Get("foo"); found {
        (foo)
    }
    // Set the value of the key "num" to 10, with the default expiration time.And add 1 to it.
    c.Set("num", 10, )
    err1 := ("num", 1)
    if err1 != nil {
        (err1)
    }
    if num, found := c.Get("num"); found {
        (num)
    }
    //Replace the value of item "foo"
    err := c.Replace("foo", "change", )
    if err != nil {
        (err)
    }

    if foo, found := c.Get("foo"); found {
        (foo)
    }
    //Get the number of the item in the cache
    c.Set("test", "hehe", )
    num := ()
    (num)
    //Delete the item in the cache
    c.Delete("foo")
    if _, found := c.Get("foo"); !found {
        ("delete")
    }

}