From a35f42bc2e4c29a1583fbc8900c14ec0ce5533d2 Mon Sep 17 00:00:00 2001 From: Marc Pervaz Boocha Date: Mon, 24 Feb 2025 10:37:50 +0530 Subject: Added examples and documentation --- examples/basic_usage/main.go | 42 ++++++++++++++++++++++++++++++++++++++++ examples/eviction_policy/main.go | 39 +++++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 examples/basic_usage/main.go create mode 100644 examples/eviction_policy/main.go (limited to 'examples') diff --git a/examples/basic_usage/main.go b/examples/basic_usage/main.go new file mode 100644 index 0000000..0582770 --- /dev/null +++ b/examples/basic_usage/main.go @@ -0,0 +1,42 @@ +package main + +import ( + "fmt" + "time" + + "github.com/marcthe12/cache" +) + +func main() { + // Create an in-memory cache + db, err := cache.OpenMem[string, string]("example") + if err != nil { + fmt.Println("Error:", err) + return + } + defer db.Close() + + // Set a value with a TTL of 5 seconds + err = db.Set("key1", "value1", 5*time.Second) + if err != nil { + fmt.Println("Set Error:", err) + return + } + + // Get the value + value, ttl, err := db.GetValue("key1") + if err != nil { + fmt.Println("Get Error:", err) + } else { + fmt.Printf("Got value: %s, TTL: %s\n", value, ttl) + } + + // Wait for 6 seconds and try to get the value again + time.Sleep(6 * time.Second) + value, ttl, err = db.GetValue("key1") + if err != nil { + fmt.Println("Get Error after TTL:", err) + } else { + fmt.Printf("Got value after TTL: %s, TTL: %s\n", value, ttl) + } +} diff --git a/examples/eviction_policy/main.go b/examples/eviction_policy/main.go new file mode 100644 index 0000000..a9c8577 --- /dev/null +++ b/examples/eviction_policy/main.go @@ -0,0 +1,39 @@ +package main + +import ( + "fmt" + + "code.qburst.com/marcpervaz//cache" +) + +func main() { + // Create an in-memory cache with LRU eviction policy + db, err := cache.OpenMem[string, string]("example", cache.WithPolicy(cache.PolicyLRU)) + if err != nil { + fmt.Println("Error:", err) + return + } + defer db.Close() + + // Set values + db.Set("key1", "value1", 0) + db.Set("key2", "value2", 0) + db.Set("key3", "value3", 0) + + // Access some keys + db.GetValue("key1") + db.GetValue("key2") + + // Add another key to trigger eviction + db.Set("key4", "value4", 0) + + // 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) + } + } +} -- cgit v1.2.3-70-g09d2