前两天业务里边需要一个需求需要用到一个带有时效性的单机缓存,对于数据不要求固化存储,于是乎就自己写了一个简单的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 5 minutes, and which // purges expired items every 30 seconds c := cache.New(10*time.Minute, 30*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 10, with the default expiration time.And add 1 to it. c.Set("num", 10, cache.DefaultExpiration) err1 := c.Increment("num", 1) 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") } }