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
|
package main
import (
"fmt"
"os"
"time"
"go.sudomsg.com/cache"
)
func main() {
// Create an in-memory cache with LRU eviction policy
db, err := cache.OpenMem[string, string](
cache.WithPolicy(cache.PolicyLRU),
cache.WithMaxCost(30),
cache.SetCleanupTime(1*time.Second),
)
if err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
defer func() {
err := db.Close()
if err != nil {
fmt.Println("Error:", err)
}
}()
// Set values
if err := db.Set("key1", "value1", 0); err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
if err := db.Set("key2", "value2", 0); err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
if err := db.Set("key3", "value3", 0); err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
// Access some keys
if _, _, err := db.GetValue("key1"); err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
if _, _, err := db.GetValue("key2"); err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
// Add another key to trigger eviction
if err := db.Set("key4", "value4", 0); err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
time.Sleep(2 * time.Second)
// Check which keys are present
for _, key := range []string{"key1", "key2", "key3", "key4"} {
value, _, err := db.GetValue(key)
if err != nil {
fmt.Printf("Key %s not found\n", key)
} else {
fmt.Printf("Key %s found with value: %s\n", key, value)
}
}
}
|