-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexamples.go
More file actions
2108 lines (1736 loc) · 63 KB
/
examples.go
File metadata and controls
2108 lines (1736 loc) · 63 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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cachex
import (
"context"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
// ExampleAllDataTypes demonstrates usage with all common Go data types
func ExampleAllDataTypes() {
// Create a Redis client
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
// Create a base cache instance (no type parameter needed)
cache := NewRedisCache(client, nil, nil, nil)
defer cache.Close()
ctx := context.Background()
// =============================================================================
// 1. STRING TYPE
// =============================================================================
fmt.Println("=== STRING TYPE ===")
stringCache := NewTypedCache[string](cache)
// Set string value
setResult := <-stringCache.Set(ctx, "user:name", "John Doe", time.Hour)
if setResult.Error != nil {
fmt.Printf("Error setting string: %v\n", setResult.Error)
} else {
fmt.Println("✓ String set successfully")
}
// Get string value
getResult := <-stringCache.Get(ctx, "user:name")
if getResult.Error != nil {
fmt.Printf("Error getting string: %v\n", getResult.Error)
} else if getResult.Found {
fmt.Printf("✓ Retrieved string: %s\n", getResult.Value)
}
// =============================================================================
// 2. INTEGER TYPES
// =============================================================================
fmt.Println("\n=== INTEGER TYPES ===")
// int
intCache := NewTypedCache[int](cache)
<-intCache.Set(ctx, "user:age", 30, time.Hour)
intResult := <-intCache.Get(ctx, "user:age")
if intResult.Found {
fmt.Printf("✓ Retrieved int: %d\n", intResult.Value)
}
// int64
int64Cache := NewTypedCache[int64](cache)
<-int64Cache.Set(ctx, "user:timestamp", time.Now().Unix(), time.Hour)
int64Result := <-int64Cache.Get(ctx, "user:timestamp")
if int64Result.Found {
fmt.Printf("✓ Retrieved int64: %d\n", int64Result.Value)
}
// int32
int32Cache := NewTypedCache[int32](cache)
<-int32Cache.Set(ctx, "user:score", int32(95), time.Hour)
int32Result := <-int32Cache.Get(ctx, "user:score")
if int32Result.Found {
fmt.Printf("✓ Retrieved int32: %d\n", int32Result.Value)
}
// uint
uintCache := NewTypedCache[uint](cache)
<-uintCache.Set(ctx, "user:count", uint(100), time.Hour)
uintResult := <-uintCache.Get(ctx, "user:count")
if uintResult.Found {
fmt.Printf("✓ Retrieved uint: %d\n", uintResult.Value)
}
// =============================================================================
// 3. FLOATING POINT TYPES
// =============================================================================
fmt.Println("\n=== FLOATING POINT TYPES ===")
// float64
float64Cache := NewTypedCache[float64](cache)
<-float64Cache.Set(ctx, "user:balance", 1234.56, time.Hour)
float64Result := <-float64Cache.Get(ctx, "user:balance")
if float64Result.Found {
fmt.Printf("✓ Retrieved float64: %.2f\n", float64Result.Value)
}
// float32
float32Cache := NewTypedCache[float32](cache)
<-float32Cache.Set(ctx, "user:rating", float32(4.5), time.Hour)
float32Result := <-float32Cache.Get(ctx, "user:rating")
if float32Result.Found {
fmt.Printf("✓ Retrieved float32: %.1f\n", float32Result.Value)
}
// =============================================================================
// 4. BOOLEAN TYPE
// =============================================================================
fmt.Println("\n=== BOOLEAN TYPE ===")
boolCache := NewTypedCache[bool](cache)
<-boolCache.Set(ctx, "user:active", true, time.Hour)
boolResult := <-boolCache.Get(ctx, "user:active")
if boolResult.Found {
fmt.Printf("✓ Retrieved bool: %t\n", boolResult.Value)
}
// =============================================================================
// 5. SLICE TYPES
// =============================================================================
fmt.Println("\n=== SLICE TYPES ===")
// []string
stringSliceCache := NewTypedCache[[]string](cache)
hobbies := []string{"reading", "swimming", "coding"}
<-stringSliceCache.Set(ctx, "user:hobbies", hobbies, time.Hour)
stringSliceResult := <-stringSliceCache.Get(ctx, "user:hobbies")
if stringSliceResult.Found {
fmt.Printf("✓ Retrieved []string: %v\n", stringSliceResult.Value)
}
// []int
intSliceCache := NewTypedCache[[]int](cache)
scores := []int{85, 92, 78, 96}
<-intSliceCache.Set(ctx, "user:scores", scores, time.Hour)
intSliceResult := <-intSliceCache.Get(ctx, "user:scores")
if intSliceResult.Found {
fmt.Printf("✓ Retrieved []int: %v\n", intSliceResult.Value)
}
// =============================================================================
// 6. MAP TYPES
// =============================================================================
fmt.Println("\n=== MAP TYPES ===")
// map[string]string
stringMapCache := NewTypedCache[map[string]string](cache)
settings := map[string]string{
"theme": "dark",
"language": "en",
"timezone": "UTC",
}
<-stringMapCache.Set(ctx, "user:settings", settings, time.Hour)
stringMapResult := <-stringMapCache.Get(ctx, "user:settings")
if stringMapResult.Found {
fmt.Printf("✓ Retrieved map[string]string: %v\n", stringMapResult.Value)
}
// map[string]int
stringIntMapCache := NewTypedCache[map[string]int](cache)
stats := map[string]int{
"posts": 150,
"followers": 1200,
"following": 300,
}
<-stringIntMapCache.Set(ctx, "user:stats", stats, time.Hour)
stringIntMapResult := <-stringIntMapCache.Get(ctx, "user:stats")
if stringIntMapResult.Found {
fmt.Printf("✓ Retrieved map[string]int: %v\n", stringIntMapResult.Value)
}
// =============================================================================
// 7. STRUCT TYPES
// =============================================================================
fmt.Println("\n=== STRUCT TYPES ===")
// Simple struct
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Active bool `json:"active"`
Score float64 `json:"score"`
}
userCache := NewTypedCache[User](cache)
user := User{
ID: 1,
Name: "Jane Smith",
Email: "jane@example.com",
Active: true,
Score: 95.5,
}
<-userCache.Set(ctx, "user:profile", user, time.Hour)
userResult := <-userCache.Get(ctx, "user:profile")
if userResult.Found {
fmt.Printf("✓ Retrieved User struct: %+v\n", userResult.Value)
}
// Complex nested struct
type Address struct {
Street string `json:"street"`
City string `json:"city"`
Country string `json:"country"`
ZipCode string `json:"zip_code"`
}
type Company struct {
Name string `json:"name"`
Address Address `json:"address"`
Founded int `json:"founded"`
}
type Employee struct {
ID int `json:"id"`
Name string `json:"name"`
Company Company `json:"company"`
Skills []string `json:"skills"`
Salary float64 `json:"salary"`
}
employeeCache := NewTypedCache[Employee](cache)
employee := Employee{
ID: 100,
Name: "Bob Johnson",
Company: Company{
Name: "Tech Corp",
Address: Address{
Street: "123 Tech St",
City: "San Francisco",
Country: "USA",
ZipCode: "94105",
},
Founded: 2010,
},
Skills: []string{"Go", "Python", "JavaScript", "Docker"},
Salary: 120000.0,
}
<-employeeCache.Set(ctx, "employee:100", employee, time.Hour)
employeeResult := <-employeeCache.Get(ctx, "employee:100")
if employeeResult.Found {
fmt.Printf("✓ Retrieved Employee struct: %+v\n", employeeResult.Value)
}
// =============================================================================
// 8. POINTER TYPES
// =============================================================================
fmt.Println("\n=== POINTER TYPES ===")
// *string
stringPtrCache := NewTypedCache[*string](cache)
message := "Hello, World!"
<-stringPtrCache.Set(ctx, "message:ptr", &message, time.Hour)
stringPtrResult := <-stringPtrCache.Get(ctx, "message:ptr")
if stringPtrResult.Found && stringPtrResult.Value != nil {
fmt.Printf("✓ Retrieved *string: %s\n", *stringPtrResult.Value)
}
// *int
intPtrCache := NewTypedCache[*int](cache)
number := 42
<-intPtrCache.Set(ctx, "number:ptr", &number, time.Hour)
intPtrResult := <-intPtrCache.Get(ctx, "number:ptr")
if intPtrResult.Found && intPtrResult.Value != nil {
fmt.Printf("✓ Retrieved *int: %d\n", *intPtrResult.Value)
}
// =============================================================================
// 9. INTERFACE TYPES
// =============================================================================
fmt.Println("\n=== INTERFACE TYPES ===")
// any/interface{}
anyCache := NewTypedCache[any](cache)
// Store different types as any
<-anyCache.Set(ctx, "data:mixed1", "string data", time.Hour)
<-anyCache.Set(ctx, "data:mixed2", 123, time.Hour)
<-anyCache.Set(ctx, "data:mixed3", true, time.Hour)
<-anyCache.Set(ctx, "data:mixed4", []string{"a", "b", "c"}, time.Hour)
// Retrieve and type assert
anyResult1 := <-anyCache.Get(ctx, "data:mixed1")
if anyResult1.Found {
if str, ok := anyResult1.Value.(string); ok {
fmt.Printf("✓ Retrieved any as string: %s\n", str)
}
}
anyResult2 := <-anyCache.Get(ctx, "data:mixed2")
if anyResult2.Found {
if num, ok := anyResult2.Value.(int); ok {
fmt.Printf("✓ Retrieved any as int: %d\n", num)
}
}
// =============================================================================
// 10. CUSTOM TYPES (TYPE ALIASES)
// =============================================================================
fmt.Println("\n=== CUSTOM TYPES ===")
// Type aliases
type UserID int
type Status string
type Priority int
userIDCache := NewTypedCache[UserID](cache)
statusCache := NewTypedCache[Status](cache)
priorityCache := NewTypedCache[Priority](cache)
<-userIDCache.Set(ctx, "user:id", UserID(12345), time.Hour)
<-statusCache.Set(ctx, "user:status", Status("active"), time.Hour)
<-priorityCache.Set(ctx, "task:priority", Priority(1), time.Hour)
userIDResult := <-userIDCache.Get(ctx, "user:id")
if userIDResult.Found {
fmt.Printf("✓ Retrieved UserID: %d\n", userIDResult.Value)
}
statusResult := <-statusCache.Get(ctx, "user:status")
if statusResult.Found {
fmt.Printf("✓ Retrieved Status: %s\n", statusResult.Value)
}
priorityResult := <-priorityCache.Get(ctx, "task:priority")
if priorityResult.Found {
fmt.Printf("✓ Retrieved Priority: %d\n", priorityResult.Value)
}
}
// ExampleBatchOperations demonstrates batch operations with different types
func ExampleBatchOperations() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
cache := NewRedisCache(client, nil, nil, nil)
defer cache.Close()
ctx := context.Background()
fmt.Println("\n=== BATCH OPERATIONS ===")
// MSet with mixed types using base cache
items := map[string]any{
"config:app_name": "MyApp",
"config:version": "1.0.0",
"config:debug": true,
"config:port": 8080,
"config:timeout": 30.5,
"config:features": []string{"auth", "logging", "metrics"},
"config:limits": map[string]int{"max_users": 1000, "max_requests": 10000},
}
msetResult := <-cache.MSet(ctx, items, time.Hour)
if msetResult.Error != nil {
fmt.Printf("Error in MSet: %v\n", msetResult.Error)
return
}
fmt.Println("✓ MSet completed successfully")
// MGet to retrieve multiple values
keys := []string{"config:app_name", "config:version", "config:debug", "config:port", "config:timeout"}
mgetResult := <-cache.MGet(ctx, keys...)
if mgetResult.Error != nil {
fmt.Printf("Error in MGet: %v\n", mgetResult.Error)
return
}
fmt.Println("✓ MGet results:")
for key, value := range mgetResult.Values {
fmt.Printf(" %s: %v (type: %T)\n", key, value, value)
}
}
// ExampleUtilityOperations demonstrates utility operations
func ExampleUtilityOperations() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
cache := NewRedisCache(client, nil, nil, nil)
defer cache.Close()
ctx := context.Background()
fmt.Println("\n=== UTILITY OPERATIONS ===")
// Set some test data
stringCache := NewTypedCache[string](cache)
<-stringCache.Set(ctx, "test:exists", "test value", time.Hour)
<-stringCache.Set(ctx, "test:ttl", "ttl test", 5*time.Second)
// Exists operation
existsResult := <-cache.Exists(ctx, "test:exists")
if existsResult.Found {
fmt.Println("✓ Key 'test:exists' exists")
}
// TTL operation
ttlResult := <-cache.TTL(ctx, "test:ttl")
if ttlResult.Error == nil {
fmt.Printf("✓ TTL for 'test:ttl': %v\n", ttlResult.TTL)
}
// IncrBy operation
incrResult := <-cache.IncrBy(ctx, "counter", 5, time.Hour)
if incrResult.Error == nil {
fmt.Printf("✓ Incremented counter by 5, new value: %d\n", incrResult.Int)
}
// Del operation
delResult := <-cache.Del(ctx, "test:exists", "test:ttl")
if delResult.Error == nil {
fmt.Printf("✓ Deleted %d keys\n", delResult.Count)
}
}
// ExampleWithContext demonstrates context usage
func ExampleWithContext() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
cache := NewRedisCache(client, nil, nil, nil)
defer cache.Close()
fmt.Println("\n=== CONTEXT USAGE ===")
// Create a context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Use the cache with the context
cacheWithCtx := cache.WithContext(ctx)
// Create typed caches from the context-aware cache
stringCache := NewTypedCache[string](cacheWithCtx)
// This operation will respect the context timeout
result := <-stringCache.Set(ctx, "context:test", "context value", time.Minute)
if result.Error != nil {
fmt.Printf("Error with context: %v\n", result.Error)
return
}
fmt.Println("✓ Successfully set value with context")
// Get the value back
getResult := <-stringCache.Get(ctx, "context:test")
if getResult.Found {
fmt.Printf("✓ Retrieved value with context: %s\n", getResult.Value)
}
}
// ExampleErrorHandling demonstrates error handling patterns
func ExampleErrorHandling() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
cache := NewRedisCache(client, nil, nil, nil)
defer cache.Close()
ctx := context.Background()
fmt.Println("\n=== ERROR HANDLING ===")
stringCache := NewTypedCache[string](cache)
// Try to get a non-existent key
getResult := <-stringCache.Get(ctx, "non:existent:key")
if !getResult.Found {
fmt.Println("✓ Correctly handled non-existent key")
}
// Try to set with empty key (should error)
setResult := <-stringCache.Set(ctx, "", "value", time.Hour)
if setResult.Error != nil {
fmt.Printf("✓ Correctly caught empty key error: %v\n", setResult.Error)
}
// Try to get with invalid key format
invalidResult := <-stringCache.Get(ctx, "")
if invalidResult.Error != nil {
fmt.Printf("✓ Correctly handled invalid key: %v\n", invalidResult.Error)
}
}
// ExampleRealWorldScenarios demonstrates real-world usage patterns
func ExampleRealWorldScenarios() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
cache := NewRedisCache(client, nil, nil, nil)
defer cache.Close()
ctx := context.Background()
fmt.Println("\n=== REAL-WORLD SCENARIOS ===")
// Scenario 1: User Session Management
fmt.Println("\n--- User Session Management ---")
type Session struct {
UserID int `json:"user_id"`
Username string `json:"username"`
LoginTime time.Time `json:"login_time"`
ExpiresAt time.Time `json:"expires_at"`
Roles []string `json:"roles"`
}
sessionCache := NewTypedCache[Session](cache)
session := Session{
UserID: 123,
Username: "john_doe",
LoginTime: time.Now(),
ExpiresAt: time.Now().Add(24 * time.Hour),
Roles: []string{"user", "admin"},
}
// Store session with 24-hour TTL
sessionResult := <-sessionCache.Set(ctx, "session:abc123", session, 24*time.Hour)
if sessionResult.Error == nil {
fmt.Println("✓ User session stored successfully")
}
// Retrieve session
retrievedSession := <-sessionCache.Get(ctx, "session:abc123")
if retrievedSession.Found {
fmt.Printf("✓ Retrieved session for user: %s\n", retrievedSession.Value.Username)
}
// Scenario 2: Application Configuration
fmt.Println("\n--- Application Configuration ---")
type AppConfig struct {
DatabaseURL string `json:"database_url"`
APIVersion string `json:"api_version"`
Features map[string]bool `json:"features"`
Limits map[string]int `json:"limits"`
Secrets map[string]string `json:"secrets"`
}
configCache := NewTypedCache[AppConfig](cache)
config := AppConfig{
DatabaseURL: "postgres://localhost:5432/myapp",
APIVersion: "v1.2.0",
Features: map[string]bool{
"auth": true,
"logging": true,
"metrics": false,
"debug": false,
},
Limits: map[string]int{
"max_connections": 100,
"rate_limit": 1000,
"cache_ttl": 3600,
},
Secrets: map[string]string{
"jwt_secret": "super-secret-key",
"api_key": "api-key-123",
},
}
<-configCache.Set(ctx, "app:config", config, time.Hour)
fmt.Println("✓ Application configuration cached")
// Scenario 3: E-commerce Product Catalog
fmt.Println("\n--- E-commerce Product Catalog ---")
type Product struct {
ID int `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Price float64 `json:"price"`
Currency string `json:"currency"`
Category string `json:"category"`
Tags []string `json:"tags"`
Attributes map[string]string `json:"attributes"`
InStock bool `json:"in_stock"`
StockCount int `json:"stock_count"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
productCache := NewTypedCache[Product](cache)
product := Product{
ID: 1001,
Name: "Wireless Bluetooth Headphones",
Description: "High-quality wireless headphones with noise cancellation",
Price: 199.99,
Currency: "USD",
Category: "Electronics",
Tags: []string{"wireless", "bluetooth", "noise-cancellation", "audio"},
Attributes: map[string]string{
"brand": "TechSound",
"model": "TS-WH1000",
"color": "Black",
"battery": "30 hours",
"connectivity": "Bluetooth 5.0",
},
InStock: true,
StockCount: 50,
CreatedAt: time.Now().Add(-7 * 24 * time.Hour),
UpdatedAt: time.Now(),
}
<-productCache.Set(ctx, "product:1001", product, 2*time.Hour)
fmt.Println("✓ Product catalog item cached")
// Scenario 4: Analytics and Metrics
fmt.Println("\n--- Analytics and Metrics ---")
type Metrics struct {
Timestamp time.Time `json:"timestamp"`
PageViews int64 `json:"page_views"`
UniqueUsers int64 `json:"unique_users"`
BounceRate float64 `json:"bounce_rate"`
TopPages []string `json:"top_pages"`
UserAgents map[string]int64 `json:"user_agents"`
Countries map[string]int64 `json:"countries"`
}
metricsCache := NewTypedCache[Metrics](cache)
metrics := Metrics{
Timestamp: time.Now(),
PageViews: 15420,
UniqueUsers: 8930,
BounceRate: 0.35,
TopPages: []string{"/home", "/products", "/about", "/contact"},
UserAgents: map[string]int64{
"Chrome": 8500,
"Firefox": 3200,
"Safari": 2100,
"Edge": 1620,
},
Countries: map[string]int64{
"US": 4500,
"UK": 2100,
"CA": 1800,
"DE": 1200,
"FR": 980,
},
}
<-metricsCache.Set(ctx, "analytics:daily:2024-01-15", metrics, 7*24*time.Hour)
fmt.Println("✓ Daily analytics metrics cached")
// Scenario 5: Cache-Aside Pattern with Type Safety
fmt.Println("\n--- Cache-Aside Pattern ---")
// Define User type and create userCache for this function
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Active bool `json:"active"`
Score float64 `json:"score"`
}
userCache := NewTypedCache[User](cache)
// Simulate a function that fetches user data from database
fetchUserFromDB := func(userID int) (User, error) {
// Simulate database call
time.Sleep(10 * time.Millisecond)
return User{
ID: userID,
Name: fmt.Sprintf("User %d", userID),
Email: fmt.Sprintf("user%d@example.com", userID),
Active: true,
Score: float64(userID * 10),
}, nil
}
// Cache-aside pattern implementation
getUserWithCache := func(userID int) (User, error) {
// Try to get from cache first
cacheKey := fmt.Sprintf("user:%d", userID)
cachedResult := <-userCache.Get(ctx, cacheKey)
if cachedResult.Found && cachedResult.Error == nil {
fmt.Printf("✓ Cache hit for user %d\n", userID)
return cachedResult.Value, nil
}
// Cache miss - fetch from database
fmt.Printf("✗ Cache miss for user %d, fetching from DB\n", userID)
user, err := fetchUserFromDB(userID)
if err != nil {
return User{}, err
}
// Store in cache for next time
<-userCache.Set(ctx, cacheKey, user, time.Hour)
fmt.Printf("✓ Stored user %d in cache\n", userID)
return user, nil
}
// Test cache-aside pattern
user1, _ := getUserWithCache(1)
fmt.Printf("✓ Retrieved user: %s\n", user1.Name)
// Second call should hit cache
user1Again, _ := getUserWithCache(1)
fmt.Printf("✓ Retrieved user again: %s\n", user1Again.Name)
}
// ExamplePerformance demonstrates performance considerations
func ExamplePerformance() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
cache := NewRedisCache(client, nil, nil, nil)
defer cache.Close()
ctx := context.Background()
fmt.Println("\n=== PERFORMANCE CONSIDERATIONS ===")
// Performance test: Batch operations vs individual operations
fmt.Println("\n--- Batch vs Individual Operations ---")
// Individual operations
start := time.Now()
stringCache := NewTypedCache[string](cache)
for i := 0; i < 100; i++ {
<-stringCache.Set(ctx, fmt.Sprintf("individual:%d", i), fmt.Sprintf("value%d", i), time.Hour)
}
individualTime := time.Since(start)
fmt.Printf("✓ 100 individual Set operations: %v\n", individualTime)
// Batch operations
start = time.Now()
batchItems := make(map[string]any)
for i := 0; i < 100; i++ {
batchItems[fmt.Sprintf("batch:%d", i)] = fmt.Sprintf("value%d", i)
}
<-cache.MSet(ctx, batchItems, time.Hour)
batchTime := time.Since(start)
fmt.Printf("✓ 100 batch MSet operations: %v\n", batchTime)
fmt.Printf("✓ Batch operations are %.2fx faster\n", float64(individualTime)/float64(batchTime))
// Memory usage consideration: Large objects
fmt.Println("\n--- Large Object Handling ---")
type LargeData struct {
ID int `json:"id"`
Data []byte `json:"data"`
Metadata map[string]string `json:"metadata"`
}
largeCache := NewTypedCache[LargeData](cache)
// Create a large object (1MB of data)
largeData := LargeData{
ID: 1,
Data: make([]byte, 1024*1024), // 1MB
Metadata: map[string]string{
"size": "1MB",
"type": "test_data",
"created": time.Now().Format(time.RFC3339),
},
}
// Fill with some data
for i := range largeData.Data {
largeData.Data[i] = byte(i % 256)
}
start = time.Now()
<-largeCache.Set(ctx, "large:object", largeData, time.Hour)
largeSetTime := time.Since(start)
fmt.Printf("✓ Stored 1MB object in: %v\n", largeSetTime)
start = time.Now()
largeResult := <-largeCache.Get(ctx, "large:object")
largeGetTime := time.Since(start)
if largeResult.Found {
fmt.Printf("✓ Retrieved 1MB object in: %v\n", largeGetTime)
fmt.Printf("✓ Object size: %d bytes\n", len(largeResult.Value.Data))
}
}
// ExampleAdvancedPatterns demonstrates advanced caching patterns
func ExampleAdvancedPatterns() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
cache := NewRedisCache(client, nil, nil, nil)
defer cache.Close()
ctx := context.Background()
fmt.Println("\n=== ADVANCED CACHING PATTERNS ===")
// Create typed cache for string operations
stringCache := NewTypedCache[string](cache)
// Define User type for this function
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Active bool `json:"active"`
Score float64 `json:"score"`
}
// Pattern 1: Write-Through Cache
fmt.Println("\n--- Write-Through Cache Pattern ---")
type WriteThroughCache[T any] struct {
cache Cache
writeFunc func(string, T) error
}
// Simulate database write
writeToDB := func(key string, value string) error {
fmt.Printf("✓ Writing to database: %s = %s\n", key, value)
return nil
}
wtCache := &WriteThroughCache[string]{
cache: cache,
writeFunc: writeToDB,
}
// Write-through implementation
writeThrough := func(key string, value string, ttl time.Duration) error {
// Write to cache
result := <-cache.Set(ctx, key, value, ttl)
if result.Error != nil {
return result.Error
}
// Write to database
return wtCache.writeFunc(key, value)
}
writeThrough("write:through:test", "write-through value", time.Hour)
fmt.Println("✓ Write-through pattern completed")
// Pattern 2: Cache Invalidation
fmt.Println("\n--- Cache Invalidation Pattern ---")
// Set up some related data
userCache := NewTypedCache[User](cache)
settingsCache := NewTypedCache[map[string]string](cache)
user := User{ID: 1, Name: "John", Email: "john@example.com", Active: true, Score: 95.5}
<-userCache.Set(ctx, "user:1", user, time.Hour)
<-userCache.Set(ctx, "user:1:profile", user, time.Hour)
<-settingsCache.Set(ctx, "user:1:settings", map[string]string{"theme": "dark"}, time.Hour)
// Invalidate all user-related cache entries
invalidateUserCache := func(userID int) {
keys := []string{
fmt.Sprintf("user:%d", userID),
fmt.Sprintf("user:%d:profile", userID),
fmt.Sprintf("user:%d:settings", userID),
}
delResult := <-cache.Del(ctx, keys...)
if delResult.Error == nil {
fmt.Printf("✓ Invalidated %d cache entries for user %d\n", delResult.Count, userID)
}
}
invalidateUserCache(1)
fmt.Println("✓ Cache invalidation pattern completed")
// Pattern 3: Cache-Aside Pattern
fmt.Println("\n--- Cache-Aside Pattern ---")
cacheAside := func(key string) (string, error) {
// Try to get from cache first
result := <-stringCache.Get(ctx, key)
if result.Found {
fmt.Printf("✓ Cache hit for key: %s\n", key)
return result.Value, nil
}
// Cache miss - fetch from database
fmt.Printf("✗ Cache miss for key: %s, fetching from database\n", key)
dbValue := "data from database"
// Store in cache for next time
<-stringCache.Set(ctx, key, dbValue, time.Hour)
return dbValue, nil
}
value, err := cacheAside("cache:aside:test")
if err == nil {
fmt.Printf("✓ Cache-aside pattern result: %s\n", value)
}
// Pattern 4: Rate Limiting with Cache
fmt.Println("\n--- Rate Limiting Pattern ---")
rateLimit := func(userID int, limit int, window time.Duration) bool {
key := fmt.Sprintf("rate:limit:%d", userID)
// Get current count
result := <-cache.IncrBy(ctx, key, 1, window)
if result.Error != nil {
return false
}
if result.Int == 1 {
// First request in window
fmt.Printf("✓ First request for user %d in window\n", userID)
return true
}
if result.Int > int64(limit) {
fmt.Printf("✗ Rate limit exceeded for user %d: %d/%d\n", userID, result.Int, limit)
return false
}
fmt.Printf("✓ Request allowed for user %d: %d/%d\n", userID, result.Int, limit)
return true
}
// Test rate limiting
allowed1 := rateLimit(123, 5, time.Minute)
allowed2 := rateLimit(123, 5, time.Minute)
allowed3 := rateLimit(123, 5, time.Minute)
fmt.Printf("✓ Rate limiting results: %t, %t, %t\n", allowed1, allowed2, allowed3)
}
// ExampleAdvancedTypes demonstrates advanced Go types
func ExampleAdvancedTypes() {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
cache := NewRedisCache(client, nil, nil, nil)
defer cache.Close()
ctx := context.Background()
fmt.Println("\n=== ADVANCED TYPES ===")
// Channel types
fmt.Println("\n--- Channel Types ---")
ch := make(chan string, 1)
ch <- "channel message"
close(ch)
// Note: Channels can't be serialized directly, but we can store their state
channelStateCache := NewTypedCache[bool](cache)
<-channelStateCache.Set(ctx, "channel:active", true, time.Hour)
// Function types (stored as metadata)
fmt.Println("\n--- Function Metadata ---")
funcCache := NewTypedCache[map[string]any](cache)
funcMetadata := map[string]any{
"name": "processData",
"version": "1.0",
"enabled": true,
"timeout": 30,
}
<-funcCache.Set(ctx, "function:metadata", funcMetadata, time.Hour)
// Complex nested types with interfaces
fmt.Println("\n--- Complex Nested Types ---")
// Note: Interface types need special handling in serialization
configCache := NewTypedCache[map[string]any](cache)
configData := map[string]any{
"name": "MyApp",
"version": "2.0.0",
"environment": "production",
"settings": map[string]any{
"timeout": 30,
"debug": false,
"host": "localhost",
},
}
<-configCache.Set(ctx, "app:config", configData, time.Hour)
configResult := <-configCache.Get(ctx, "app:config")
if configResult.Found {
fmt.Printf("✓ Retrieved complex config: %+v\n", configResult.Value)
}
// Time types
fmt.Println("\n--- Time Types ---")
timeCache := NewTypedCache[time.Time](cache)
now := time.Now()
<-timeCache.Set(ctx, "system:startup", now, time.Hour)
timeResult := <-timeCache.Get(ctx, "system:startup")
if timeResult.Found {
fmt.Printf("✓ Retrieved time: %v\n", timeResult.Value)
}
// Duration types
durationCache := NewTypedCache[time.Duration](cache)
<-durationCache.Set(ctx, "config:timeout", 30*time.Second, time.Hour)
durationResult := <-durationCache.Get(ctx, "config:timeout")
if durationResult.Found {