天天看點

golang的一個基于記憶體的key-value 緩存

前兩天業務裡邊需要一個需求需要用到一個帶有時效性的單機緩存,對于資料不要求固化存儲,于是乎就自己寫了一個簡單的key-value的memcache。

整個cache提供了,set、get、replace,delete等方法,在初始化cache的時候可以根據業務需求初始化每個item在cache中的失效時間,以及檢測删除過期資料的時間周期。提供了一個對int型value計數的方法Increment。

緩存源碼的連結,也可以通過 go get github.com/UncleBig/goCache 的方式擷取。 下面

下面是一個使用的例子,對每個方法都有簡要的說明

package example

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

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

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

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

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

}