-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredis.go
105 lines (85 loc) · 2.59 KB
/
redis.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
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"context"
"fmt"
"time"
"github.com/hyp3rd/hypercache"
"github.com/hyp3rd/hypercache/backend"
"github.com/hyp3rd/hypercache/backend/redis"
"github.com/hyp3rd/hypercache/types"
)
func main() {
redisStore, err := redis.New(
redis.WithAddr("localhost:6379"),
redis.WithPassword("k7oMs2G5bc4mRN45jPZjLBZxuMFrCLahvPn648Zwq1lT41gSYZqapBRnSF2L995FaYcZBz8c7xkKXku94HeReDgdwBu1N4CzgfQ94Z504hjfzrST1u0idVkbXe8ust"),
redis.WithDB(0),
)
if err != nil {
panic(err)
}
conf := &hypercache.Config[backend.Redis]{
BackendType: "redis",
RedisOptions: []backend.Option[backend.Redis]{
backend.WithRedisClient(redisStore.Client),
backend.WithCapacity[backend.Redis](20),
},
HyperCacheOptions: []hypercache.Option[backend.Redis]{
hypercache.WithEvictionInterval[backend.Redis](time.Second * 5),
},
}
hyperCache, err := hypercache.New(hypercache.GetDefaultManager(), conf)
if err != nil {
panic(err)
}
fmt.Println("setting 50 items to the cache")
for i := 0; i < 50; i++ {
err = hyperCache.Set(context.TODO(), fmt.Sprintf("key-%d", i), fmt.Sprintf("value-%d", i), time.Hour)
if err != nil {
panic(err)
}
}
fmt.Println("count", hyperCache.Count())
fmt.Println("capacity", hyperCache.Capacity())
fmt.Println("fetching all items (sorted by key, ascending, filtered by value != 'value-16')")
// Apply filters
// Define a filter function
itemsFilterFunc := func(item *types.Item) bool {
// return time.Since(item.LastAccess) > 1*time.Microsecond
return item.Value != "value-16"
}
sortByFilter := backend.WithSortBy(types.SortByKey.String())
// sortOrderFilter := backend.WithSortOrderAsc(true)
// Create a filterFuncFilter with the defined filter function
filter := backend.WithFilterFunc(itemsFilterFunc)
// Retrieve the list of items from the cache
allItems, err := hyperCache.List(context.TODO(), sortByFilter, filter)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("printing all items")
// Print the list of items
for _, item := range allItems {
fmt.Println(item.Key, item.Value)
}
fmt.Println("count", hyperCache.Count())
fmt.Println("capacity", hyperCache.Capacity())
fmt.Println("sleep for 5 seconds to trigger eviction")
time.Sleep(time.Second * 5)
fmt.Println("fetching all items again")
allItems, err = hyperCache.List(context.TODO())
if err != nil {
fmt.Println(err)
return
}
fmt.Println("printing all items")
// Print the list of items
for _, item := range allItems {
fmt.Println(item.Key, item.Value)
}
fmt.Println("count", hyperCache.Count())
value, ok := hyperCache.Get("key-49")
if ok {
fmt.Println(value)
}
}