aboutsummaryrefslogtreecommitdiffstats
path: root/examples/eviction_policy_persistant/main.go
blob: fc7cc3251196fe4574c6c511cc2cb707efef7f88 (plain) (blame)
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
package main

import (
	"fmt"
	"os"
	"time"

	"github.com/marcthe12/cache"
)

func main() {
	// Create an in-memory cache with LRU eviction policy
	db, err := cache.Open[int, int](
		"cache.db",
		cache.WithPolicy(cache.PolicyLRU),
		cache.WithMaxCost(20),
		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)
		}
	}()

	fmt.Println("Loaded Cache")
	// Check which keys are present
	for n := range 4 {
		key := n + 1
		value, _, err := db.GetValue(key)

		if err != nil {
			fmt.Printf("Key %d not found\n", key)
		} else {
			fmt.Printf("Key %d found with value: %d\n", key, value)
		}
	}

	fmt.Println("Set Values")
	// Set values
	if err := db.Set(1, -1, 10*time.Second); err != nil {
		fmt.Println("Error:", err)
		os.Exit(1)
	}

	if err := db.Set(2, -2, 10*time.Second); err != nil {
		fmt.Println("Error:", err)
		os.Exit(1)
	}

	if err := db.Set(3, -3, 10*time.Second); err != nil {
		fmt.Println("Error:", err)
		os.Exit(1)
	}

	// Access some keys
	if _, _, err := db.GetValue(1); err != nil {
		fmt.Println("Error:", err)
		os.Exit(1)
	}

	if _, _, err := db.GetValue(2); err != nil {
		fmt.Println("Error:", err)
		os.Exit(1)
	}

	fmt.Println("Add Key 4")
	// Add another key to trigger eviction
	if err := db.Set(4, -4, 0); err != nil {
		fmt.Println("Error:", err)
		os.Exit(1)
	}

	fmt.Println("Sleep")
	time.Sleep(2 * time.Second)

	fmt.Println("Resume")
	// Check which keys are present
	for n := range 4 {
		key := n + 1
		value, _, err := db.GetValue(key)

		if err != nil {
			fmt.Printf("Key %d not found\n", key)
		} else {
			fmt.Printf("Key %d found with value: %d\n", key, value)
		}
	}
}