cache2go是一个Go的并发安全缓存库,具有到期和访问计数器的功能。
示例代码:
package maiimport ( "github.com/muesli/cache2go" "fmt" "time")// Keys & values i cache2go ca be off arbitrary types, e.g. a struct.type myStruct struct { text strig moreData []byte}fuc mai() { // Accessig a ew cache table for the first time will create it. cache := cache2go.Cache("myCache") // We will put a ew item i the cache. It will expire after // ot beig accessed via Value(key) for more tha 5 secods. val := myStruct{"This is a test!", []byte{}} cache.Add("someKey", 5*time.Secod, &val) // Let's retrieve the item from the cache. res, err := cache.Value("someKey") if err == il { fmt.Pritl("Foud value i cache:", res.Data().(*myStruct).text) } else { fmt.Pritl("Error retrievig value from cache:", err) } // Wait for the item to expire i cache. time.Sleep(6 * time.Secod) res, err = cache.Value("someKey") if err != il { fmt.Pritl("Item is ot cached (aymore).") } // Add aother item that ever expires. cache.Add("someKey", 0, &val) // cache2go supports a few hady callbacks ad loadig mechaisms. cache.SetAboutToDeleteItemCallback(fuc(e *cache2go.CacheItem) { fmt.Pritl("Deletig:", e.Key(), e.Data().(*myStruct).text, e.CreatedO()) }) // Remove the item from the cache. cache.Delete("someKey") // Ad wipe the etire cache table. cache.Flush()}go ru mycachedapp.go










评论