github.com/unionj-cloud/go-doudou/v2@v2.3.5/toolkit/cache/example_cache_test.go (about) 1 package cache_test 2 3 import ( 4 "context" 5 "fmt" 6 "time" 7 8 "github.com/redis/go-redis/v9" 9 10 "github.com/unionj-cloud/go-doudou/v2/toolkit/cache" 11 ) 12 13 type Object struct { 14 Str string 15 Num int 16 } 17 18 func Example_basicUsage() { 19 ring := redis.NewRing(&redis.RingOptions{ 20 Addrs: map[string]string{ 21 "server1": ":6379", 22 "server2": ":6380", 23 }, 24 }) 25 26 mycache := cache.New(&cache.Options{ 27 Redis: ring, 28 LocalCache: cache.NewTinyLFU(1000, time.Minute), 29 }) 30 31 ctx := context.TODO() 32 key := "mykey" 33 obj := &Object{ 34 Str: "mystring", 35 Num: 42, 36 } 37 38 if err := mycache.Set(&cache.Item{ 39 Ctx: ctx, 40 Key: key, 41 Value: obj, 42 TTL: time.Hour, 43 }); err != nil { 44 panic(err) 45 } 46 47 var wanted Object 48 if err := mycache.Get(ctx, key, &wanted); err == nil { 49 fmt.Println(wanted) 50 } 51 52 // Output: {mystring 42} 53 } 54 55 func Example_advancedUsage() { 56 ring := redis.NewRing(&redis.RingOptions{ 57 Addrs: map[string]string{ 58 "server1": ":6379", 59 "server2": ":6380", 60 }, 61 }) 62 63 mycache := cache.New(&cache.Options{ 64 Redis: ring, 65 LocalCache: cache.NewTinyLFU(1000, time.Minute), 66 }) 67 68 obj := new(Object) 69 err := mycache.Once(&cache.Item{ 70 Key: "mykey", 71 Value: obj, // destination 72 Do: func(*cache.Item) (interface{}, error) { 73 return &Object{ 74 Str: "mystring", 75 Num: 42, 76 }, nil 77 }, 78 }) 79 if err != nil { 80 panic(err) 81 } 82 fmt.Println(obj) 83 // Output: &{mystring 42} 84 }