func main() { cache := cache2go.Cache("myCache") // The data loader gets called automatically whenever something // tries to retrieve a non-existing key from the cache. cache.SetDataLoader(func(key interface{}) *cache2go.CacheItem { // Apply some clever loading logic here, e.g. read values for // this key from database, network or file. val := "This is a test with key " + key.(string) // This helper method creates the cached item for us. Yay! item := cache2go.CreateCacheItem(key, 0, val) return &item }) // Let's retrieve a few auto-generated items from the cache. for i := 0; i < 10; i++ { res, err := cache.Value("someKey_" + strconv.Itoa(i)) if err == nil { fmt.Println("Found value in cache:", res.Data()) } else { fmt.Println("Error retrieving value from cache:", err) } } }
func main() { // Accessing a new cache table for the first time will create it. cache := cache2go.Cache("myCache") // We will put a new item in the cache. It will expire after // not being accessed via Value(key) for more than 5 seconds. val := myStruct{"This is a test!", []byte{}} cache.Cache("someKey", 5*time.Second, &val) // Let's retrieve the item from the cache. res, err := cache.Value("someKey") if err == nil { fmt.Println("Found value in cache:", res.Data().(*myStruct).text) } else { fmt.Println("Error retrieving value from cache:", err) } // Wait for the item to expire in cache. time.Sleep(6 * time.Second) res, err = cache.Value("someKey") if err != nil { fmt.Println("Item is not cached (anymore).") } // Add another item that never expires. cache.Cache("someKey", 0, &val) // cache2go supports a few handy callbacks and loading mechanisms. cache.SetAboutToDeleteItemCallback(func(e *cache2go.CacheItem) { fmt.Println("Deleting:", e.Key(), e.Data().(*myStruct).text, e.CreatedOn()) }) // Remove the item from the cache. cache.Delete("someKey") // And wipe the entire cache table. cache.Flush() }
func NewCacheStore() *CacheStore { cache := cache2go.Cache("cacheStore") return &CacheStore{cache: cache} }