-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
197 lines (165 loc) · 5.31 KB
/
main.go
File metadata and controls
197 lines (165 loc) · 5.31 KB
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/redis/go-redis/v9"
"github.com/vnykmshr/obcache-go/pkg/obcache"
)
// User represents a simple user struct
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
// Simulate an expensive database operation
func getUserFromDatabase(userID int) (*User, error) {
// Simulate database latency
time.Sleep(100 * time.Millisecond)
// Simulate database query
user := &User{
ID: userID,
Name: fmt.Sprintf("User %d", userID),
Email: fmt.Sprintf("user%d@example.com", userID),
}
return user, nil
}
func main() {
fmt.Println("🚀 obcache-go Redis Adapter Example")
fmt.Println("===================================")
// Example 1: Basic Redis cache usage
fmt.Println("\n1. Basic Redis Cache Operations")
basicRedisExample()
// Example 2: Function wrapping with Redis cache
fmt.Println("\n2. Function Wrapping with Redis Cache")
functionWrappingExample()
// Example 3: Distributed caching scenario
fmt.Println("\n3. Distributed Caching with Custom Client")
distributedCachingExample()
}
func basicRedisExample() {
// Create a Redis cache with simple address
config := obcache.NewRedisConfig("localhost:6379").
WithRedis(&obcache.RedisConfig{
KeyPrefix: "example:",
}).
WithDefaultTTL(30 * time.Minute)
cache, err := obcache.New(config)
if err != nil {
log.Printf("Failed to create Redis cache: %v", err)
fmt.Println("⚠️ Make sure Redis is running on localhost:6379")
return
}
defer cache.Close()
// Store a user in cache
user := &User{ID: 1, Name: "Alice", Email: "alice@example.com"}
err = cache.Set("user:1", user, time.Hour)
if err != nil {
log.Printf("Failed to set cache entry: %v", err)
return
}
// Retrieve user from cache
if cachedUser, found := cache.Get("user:1"); found {
fmt.Printf("✅ Found cached user: %+v\n", cachedUser)
} else {
fmt.Println("❌ User not found in cache")
}
// Show cache statistics
stats := cache.Stats()
fmt.Printf("📊 Cache Stats - Hits: %d, Misses: %d, Hit Rate: %.1f%%\n",
stats.Hits(), stats.Misses(), stats.HitRate())
}
func functionWrappingExample() {
// Create Redis cache configuration
config := obcache.NewRedisConfig("localhost:6379").
WithRedis(&obcache.RedisConfig{
KeyPrefix: "func:",
}).
WithDefaultTTL(15 * time.Minute)
cache, err := obcache.New(config)
if err != nil {
log.Printf("Failed to create Redis cache: %v", err)
fmt.Println("⚠️ Make sure Redis is running on localhost:6379")
return
}
defer cache.Close()
// Wrap the expensive function with caching
cachedGetUser := obcache.Wrap(cache, getUserFromDatabase,
obcache.WithTTL(5*time.Minute))
// First call - will execute the function and cache the result
start := time.Now()
user1, err := cachedGetUser(123)
if err != nil {
log.Printf("Error getting user: %v", err)
return
}
duration1 := time.Since(start)
fmt.Printf("🔄 First call (cache miss): %+v (took %v)\n", user1, duration1)
// Second call - will return from cache
start = time.Now()
user2, err := cachedGetUser(123)
if err != nil {
log.Printf("Error getting user: %v", err)
return
}
duration2 := time.Since(start)
fmt.Printf("⚡ Second call (cache hit): %+v (took %v)\n", user2, duration2)
// Show performance improvement
fmt.Printf("🚀 Speed improvement: %.1fx faster\n", float64(duration1)/float64(duration2))
// Show cache statistics
stats := cache.Stats()
fmt.Printf("📊 Cache Stats - Hits: %d, Misses: %d, Hit Rate: %.1f%%\n",
stats.Hits(), stats.Misses(), stats.HitRate())
}
func distributedCachingExample() {
// Create a Redis client with custom configuration for distributed scenario
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // No password
DB: 1, // Use database 1 for this example
PoolSize: 10,
MinIdleConns: 5,
MaxRetries: 3,
})
// Test the connection
if err := client.Ping(context.Background()).Err(); err != nil {
log.Printf("Failed to connect to Redis: %v", err)
fmt.Println("⚠️ Make sure Redis is running on localhost:6379")
return
}
// Create cache configuration with the custom client
config := obcache.NewRedisConfigWithClient(client).
WithRedis(&obcache.RedisConfig{
KeyPrefix: "distributed:",
}).
WithDefaultTTL(1 * time.Hour)
cache, err := obcache.New(config)
if err != nil {
log.Printf("Failed to create distributed cache: %v", err)
return
}
defer cache.Close()
// Simulate distributed caching scenario
fmt.Println("🌐 Simulating distributed caching...")
// Store some data that could be shared across multiple application instances
sessionData := map[string]interface{}{
"user_id": 42,
"username": "distributed_user",
"session_id": "sess_123456789",
"expires_at": time.Now().Add(2 * time.Hour),
}
err = cache.Set("session:sess_123456789", sessionData, 2*time.Hour)
if err != nil {
log.Printf("Failed to store session: %v", err)
return
}
// Retrieve session data (could be from any application instance)
if session, found := cache.Get("session:sess_123456789"); found {
fmt.Printf("✅ Retrieved session data: %+v\n", session)
}
// Show all keys with our prefix
keys := cache.Keys()
fmt.Printf("🔑 Found %d keys in distributed cache: %v\n", len(keys), keys)
fmt.Println("✨ Distributed caching example completed!")
}