jsoncache(JSON caching)
Type-safe JSON caching functionality with Redis backend, supporting generic types for compile-time type safety.
The jsoncache module provides type-safe JSON caching functionality with Redis backend, supporting generic types for compile-time type safety.
Features
- Type-safe JSON caching with generics
- Redis backend support
- Automatic JSON marshaling/unmarshaling
- Prefix-based key management
- Error handling with context
Basic Usage
1package main
2
3import (
4 "context"
5 "fmt"
6
7 "github.com/redis/go-redis/v9"
8
9 "github.com/crazyfrankie/frx/jsoncache"
10)
11
12type User struct {
13 ID int64 `json:"id"`
14 Name string `json:"name"`
15 Email string `json:"email"`
16}
17
18func main() {
19 // Initialize Redis client
20 rdb := redis.NewClient(&redis.Options{
21 Addr: "localhost:6379",
22 })
23
24 // Create JSON cache for User type
25 userCache := jsoncache.New[User]("user:", rdb)
26
27 ctx := context.Background()
28
29 // Save user to cache
30 user := &User{
31 ID: 1,
32 Name: "John Doe",
33 Email: "john@example.com",
34 }
35
36 err := userCache.Save(ctx, "123", user)
37 if err != nil {
38 panic(err)
39 }
40
41 // Get user from cache
42 cachedUser, err := userCache.Get(ctx, "123")
43 if err != nil {
44 panic(err)
45 }
46
47 fmt.Printf("Cached user: %+v\n", cachedUser)
48
49 // Delete user from cache
50 err = userCache.Delete(ctx, "123")
51 if err != nil {
52 panic(err)
53 }
54}