-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache_examples_test.go
More file actions
79 lines (64 loc) · 1.75 KB
/
cache_examples_test.go
File metadata and controls
79 lines (64 loc) · 1.75 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package loadingcache_test
import (
"context"
"fmt"
"time"
"github.com/pkg/errors"
"github.com/devzero-inc/loadingcache"
)
func ExampleCache_simpleUsage() {
type Key string
type Value int
cache := loadingcache.New[Key, Value]()
// Addign some values and reading them
cache.Put("a", 1)
cache.Put("b", 2)
cache.Put("c", 3)
val1, _ := cache.Get(context.TODO(), "a") // Don't forget to check for errors
fmt.Printf("%v\n", val1)
val2, _ := cache.Get(context.TODO(), "b") // Don't forget to check for errors
fmt.Printf("%v\n", val2)
// Getting a value that does not exist
_, err := cache.Get(context.TODO(), "d")
if errors.Is(err, loadingcache.ErrKeyNotFound) {
fmt.Println("That key does not exist")
}
// Evicting
cache.Invalidate("a")
cache.Invalidate("b", "c")
cache.InvalidateAll()
// Output: 1
// 2
// That key does not exist
}
func ExampleCache_advancedUsage() {
type Key int
type Value string
cache := loadingcache.New(
loadingcache.WithMaxSize[Key, Value](2),
loadingcache.WithExpireAfterRead[Key, Value](2*time.Minute),
loadingcache.WithExpireAfterWrite[Key, Value](time.Minute),
loadingcache.WithRemovalListeners(
func(notification loadingcache.RemovalNotification[Key, Value]) {
fmt.Printf("Entry removed due to %s\n", notification.Reason)
},
),
loadingcache.WithLoadFunc(func(_ context.Context, key Key) (Value, error) {
fmt.Printf("Loading key %v\n", key)
return Value(fmt.Sprint(key)), nil
}),
)
cache.Put(1, "1")
val1, _ := cache.Get(context.TODO(), 1)
fmt.Printf("%v\n", val1)
val2, _ := cache.Get(context.TODO(), 2)
fmt.Printf("%v\n", val2)
val3, _ := cache.Get(context.TODO(), 3)
fmt.Printf("%v\n", val3)
// Output: 1
// Loading key 2
// 2
// Loading key 3
// Entry removed due to SIZE
// 3
}