-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget.go
More file actions
79 lines (61 loc) · 1.76 KB
/
get.go
File metadata and controls
79 lines (61 loc) · 1.76 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 main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/hyp3rd/hypercache"
"github.com/hyp3rd/hypercache/internal/constants"
)
const cacheCapacity = 10
func main() {
ctx, cancel := context.WithTimeout(context.Background(), constants.DefaultTimeout)
defer cancel()
// Create a new HyperCache with a capacity of 10
cache, err := hypercache.NewInMemoryWithDefaults(ctx, cacheCapacity)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
// Stop the cache when the program exits
defer cache.Stop(ctx)
log.Println("adding items to the cache")
// Add 10 items to the cache
for i := range 10 {
key := fmt.Sprintf("key%d", i)
val := fmt.Sprintf("val%d", i)
err = cache.Set(ctx, key, val, time.Minute)
if err != nil {
fmt.Fprintf(os.Stdout, "unexpected error: %v\n", err)
return
}
}
log.Println("fetching items from the cache using the `GetMultiple` method, key11 does not exist")
// Retrieve the specific of items from the cache
items, errs := cache.GetMultiple(ctx, "key1", "key7", "key9", "key11")
// Print the errors if any
for k, e := range errs {
log.Printf("error fetching item %s: %s\n", k, e)
}
// Print the items
for k, v := range items {
fmt.Fprintln(os.Stdout, k, v)
}
log.Println("fetching items from the cache using the `GetOrSet` method")
// Retrieve a specific of item from the cache
// If the item is not found, set it and return the value
val, err := cache.GetOrSet(ctx, "key11", "val11", time.Minute)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
fmt.Fprintln(os.Stdout, val)
log.Println("fetching items from the cache using the simple `Get` method")
item, ok := cache.Get(ctx, "key7")
if !ok {
fmt.Fprintln(os.Stdout, "item not found")
return
}
fmt.Fprintln(os.Stdout, item)
}