| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"log" |
| 6 |
"math/rand/v2" |
| 7 |
"strconv" |
| 8 |
"strings" |
| 9 |
"time" |
| 10 |
|
| 11 |
"github.com/viccon/sturdyc" |
| 12 |
) |
| 13 |
|
| 14 |
type API struct { |
| 15 |
*sturdyc.Client[string] |
| 16 |
} |
| 17 |
|
| 18 |
func NewAPI(c *sturdyc.Client[string]) *API { |
| 19 |
return &API{c} |
| 20 |
} |
| 21 |
|
| 22 |
func (a *API) GetBatch(ctx context.Context, ids []string) (map[string]string, error) { |
| 23 |
// We are going to pass a cache a key function that prefixes each id with |
| 24 |
// the string "some-prefix", and adds an -ID- separator before the actual |
| 25 |
// id. This makes it possible to save the same id for different data |
| 26 |
// sources as the keys would look something like this: some-prefix-ID-1 |
| 27 |
cacheKeyFn := a.BatchKeyFn("some-prefix") |
| 28 |
|
| 29 |
// The fetchFn is only going to retrieve the IDs that are not in the cache. |
| 30 |
fetchFn := func(_ context.Context, cacheMisses []string) (map[string]string, error) { |
| 31 |
log.Printf("Cache miss. Fetching ids: %s\n", strings.Join(cacheMisses, ", ")) |
| 32 |
// Batch functions should return a map where the key is the id of the record. |
| 33 |
// If you have storage of missing records enabled, any ID that isn't present |
| 34 |
// in this map is going to be stored as a cache miss. |
| 35 |
response := make(map[string]string, len(cacheMisses)) |
| 36 |
for _, id := range cacheMisses { |
| 37 |
response[id] = "value" |
| 38 |
} |
| 39 |
return response, nil |
| 40 |
} |
| 41 |
|
| 42 |
return a.GetOrFetchBatch(ctx, ids, cacheKeyFn, fetchFn) |
| 43 |
} |
| 44 |
|
| 45 |
func main() { |
| 46 |
// Maximum number of entries in the sturdyc. |
| 47 |
capacity := 10000 |
| 48 |
// Number of shards to use for the sturdyc. |
| 49 |
numShards := 10 |
| 50 |
// Time-to-live for cache entries. |
| 51 |
ttl := 2 * time.Hour |
| 52 |
// Percentage of entries to evict when the cache is full. Setting this |
| 53 |
// to 0 will make set a no-op if the cache has reached its capacity. |
| 54 |
evictionPercentage := 10 |
| 55 |
// Set a minimum and maximum refresh delay for the sturdyc. This is |
| 56 |
// used to spread out the refreshes for entries evenly over time. |
| 57 |
minRefreshDelay := time.Second |
| 58 |
maxRefreshDelay := time.Second * 2 |
| 59 |
// Set a synchronous refresh delay for when we want a refresh to happen synchronously. |
| 60 |
synchronousRefreshDelay := time.Second * 30 |
| 61 |
// The base for exponential backoff when retrying a refresh. |
| 62 |
retryBaseDelay := time.Millisecond * 10 |
| 63 |
|
| 64 |
// Create a cache client with the specified configuration. |
| 65 |
cacheClient := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage, |
| 66 |
sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, synchronousRefreshDelay, retryBaseDelay), |
| 67 |
) |
| 68 |
|
| 69 |
// Create a new API instance with the cache client. |
| 70 |
api := NewAPI(cacheClient) |
| 71 |
|
| 72 |
// Seed the cache with ids 1-10. |
| 73 |
log.Println("Seeding ids 1-10") |
| 74 |
ids := []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"} |
| 75 |
api.GetBatch(context.Background(), ids) |
| 76 |
log.Println("Seed completed") |
| 77 |
|
| 78 |
// To demonstrate that the records have been cached individually, we can continue |
| 79 |
// fetching a random subset of records from the original batch, plus a new |
| 80 |
// ID. By examining the logs, we should be able to see that the cache only |
| 81 |
// fetches the ID that wasn't present in the original batch, indicating that |
| 82 |
// the batch itself isn't part of the key. |
| 83 |
for i := 1; i <= 100; i++ { |
| 84 |
// Get N ids from the original batch. |
| 85 |
recordsToFetch := rand.IntN(10) + 1 |
| 86 |
batch := make([]string, recordsToFetch) |
| 87 |
copy(batch, ids[:recordsToFetch]) |
| 88 |
// Add a random ID between 1 and 100 to the batch. |
| 89 |
batch = append(batch, strconv.Itoa(rand.IntN(1000)+10)) |
| 90 |
values, _ := api.GetBatch(context.Background(), batch) |
| 91 |
log.Println(values) |
| 92 |
} |
| 93 |
} |