Debian Codegraph @

examples/basic/main.go

raw
1 package main
2
3 import (
4 "context"
5 "log"
6 "math/rand/v2"
7 "strconv"
8 "sync"
9 "sync/atomic"
10 "time"
11
12 "github.com/viccon/sturdyc"
13 )
14
15 func pickRandomValue(batches [][]string) string {
16 batch := batches[rand.IntN(len(batches))]
17 return batch[rand.IntN(len(batch))]
18 }
19
20 func demonstrateGetOrFetch(cacheClient *sturdyc.Client[int]) {
21 // The cache has built-in stampede protection where it tracks in-flight
22 // requests for every key.
23 var count atomic.Int32
24 fetchFn := func(_ context.Context) (int, error) {
25 count.Add(1)
26 time.Sleep(time.Second)
27 return 1337, nil
28 }
29
30 var wg sync.WaitGroup
31 for i := 0; i < 10; i++ {
32 wg.Add(1)
33 go func() {
34 // We can ignore the error given the fetchFn we're using.
35 val, _ := cacheClient.GetOrFetch(context.Background(), "key2", fetchFn)
36 log.Printf("got value: %d\n", val)
37 wg.Done()
38 }()
39 }
40 wg.Wait()
41
42 log.Printf("fetchFn was called %d time\n", count.Load())
43 log.Println(cacheClient.Get("key2"))
44 log.Println("")
45 }
46
47 func demonstrateGetOrFetchBatch(cacheClient *sturdyc.Client[int]) {
48 var count atomic.Int32
49 fetchFn := func(_ context.Context, ids []string) (map[string]int, error) {
50 count.Add(1)
51 time.Sleep(time.Second * 5)
52
53 response := make(map[string]int, len(ids))
54 for _, id := range ids {
55 num, _ := strconv.Atoi(id)
56 response[id] = num
57 }
58
59 return response, nil
60 }
61
62 batches := [][]string{
63 {"1", "2", "3", "4", "5"},
64 {"6", "7", "8", "9", "10"},
65 {"11", "12", "13", "14", "15"},
66 }
67
68 // We are going to pass a cache a key function that prefixes each id with
69 // the string "my-data-source", and adds an -ID- separator before the actual
70 // id. This makes it possible to save the same id for different data
71 // sources as the keys would look something like this: my-data-source-ID-1
72 keyPrefixFn := cacheClient.BatchKeyFn("my-data-source")
73
74 // Request the keys for each batch.
75 for _, batch := range batches {
76 go func() {
77 res, _ := cacheClient.GetOrFetchBatch(context.Background(), batch, keyPrefixFn, fetchFn)
78 log.Printf("got batch: %v\n", res)
79 }()
80 }
81
82 // Give the goroutines above a chance to run to ensure that the batches are in-flight.
83 time.Sleep(time.Second * 3)
84
85 // Launch another 5 goroutines that are going to pick two random IDs from any of the batches.
86 var wg sync.WaitGroup
87 for i := 0; i < 5; i++ {
88 wg.Add(1)
89 go func() {
90 ids := []string{pickRandomValue(batches), pickRandomValue(batches)}
91 res, _ := cacheClient.GetOrFetchBatch(context.Background(), ids, keyPrefixFn, fetchFn)
92 log.Printf("got batch: %v\n", res)
93 wg.Done()
94 }()
95 }
96
97 wg.Wait()
98 log.Printf("fetchFn was called %d times\n", count.Load())
99 }
100
101 func main() {
102 // Maximum number of entries in the sturdyc.
103 capacity := 10000
104 // Number of shards to use for the sturdyc.
105 numShards := 10
106 // Time-to-live for cache entries.
107 ttl := 2 * time.Hour
108 // Percentage of entries to evict when the cache is full. Setting this
109 // to 0 will make set a no-op if the cache has reached its capacity.
110 evictionPercentage := 10
111
112 // Create a cache client with the specified configuration.
113 cacheClient := sturdyc.New[int](capacity, numShards, ttl, evictionPercentage)
114
115 cacheClient.Set("key1", 99)
116 log.Println(cacheClient.Size())
117 log.Println(cacheClient.Get("key1"))
118
119 demonstrateGetOrFetch(cacheClient)
120 demonstrateGetOrFetchBatch(cacheClient)
121 }