-
-
Notifications
You must be signed in to change notification settings - Fork 513
/
Copy pathcallbacks.go
51 lines (41 loc) · 1.49 KB
/
callbacks.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package main
import (
"fmt"
"time"
"github.com/muesli/cache2go"
)
func main() {
cache := cache2go.Cache("myCache")
// This callback will be triggered every time a new item
// gets added to the cache.
cache.SetAddedItemCallback(func(entry *cache2go.CacheItem) {
fmt.Println("Added Callback 1:", entry.Key(), entry.Data(), entry.CreatedOn())
})
cache.AddAddedItemCallback(func(entry *cache2go.CacheItem) {
fmt.Println("Added Callback 2:", entry.Key(), entry.Data(), entry.CreatedOn())
})
// This callback will be triggered every time an item
// is about to be removed from the cache.
cache.SetAboutToDeleteItemCallback(func(entry *cache2go.CacheItem) {
fmt.Println("Deleting:", entry.Key(), entry.Data(), entry.CreatedOn())
})
// Caching a new item will execute the AddedItem callback.
cache.Add("someKey", 0, "This is a test!")
// Let's retrieve the item from the cache
res, err := cache.Value("someKey")
if err == nil {
fmt.Println("Found value in cache:", res.Data())
} else {
fmt.Println("Error retrieving value from cache:", err)
}
// Deleting the item will execute the AboutToDeleteItem callback.
cache.Delete("someKey")
cache.RemoveAddedItemCallbacks()
// Caching a new item that expires in 3 seconds
res = cache.Add("anotherKey", 3*time.Second, "This is another test")
// This callback will be triggered when the item is about to expire
res.SetAboutToExpireCallback(func(key interface{}) {
fmt.Println("About to expire:", key.(string))
})
time.Sleep(5 * time.Second)
}