github.com/15mga/kiwi@v0.0.2-0.20240324021231-b95d5c3ac751/util/rds/redis_test.go (about) 1 package rds 2 3 import ( 4 "fmt" 5 "testing" 6 7 "github.com/15mga/kiwi" 8 "github.com/15mga/kiwi/util" 9 "github.com/gomodule/redigo/redis" 10 "github.com/mitchellh/mapstructure" 11 "github.com/stretchr/testify/assert" 12 ) 13 14 func init() { 15 fac := func() (redis.Conn, error) { 16 return redis.Dial("tcp", "127.0.0.1:6379", 17 redis.DialDatabase(0)) 18 } 19 InitRedis( 20 ConnFac(fac), 21 ) 22 } 23 24 func TestJsonGet(t *testing.T) { 25 conn, err := GetConn() 26 assert.Nil(t, err) 27 defer conn.Close() 28 29 si := kiwi.NodeMeta{ 30 Svc: 1, 31 Ip: "127.0.0.1", 32 Port: 7300, 33 SvcId: 10000, 34 } 35 36 key := "service:register:1:gate" 37 err = JsonSet(conn, key, util.M{ 38 "1001": si, 39 }) 40 assert.Nil(t, err) 41 42 var m map[string]*kiwi.NodeMeta 43 err = JsonGet[map[string]*kiwi.NodeMeta](conn, key, &m) 44 assert.Nil(t, err) 45 assert.Equal(t, map[string]*kiwi.NodeMeta{ 46 "1001": &si, 47 }, m) 48 49 key = "test:2" 50 err = JsonSet(conn, key, util.M{ 51 "name": "95eh", 52 }) 53 assert.Nil(t, err) 54 var m1 map[string]string 55 err = JsonGet[map[string]string](conn, key, &m1) 56 assert.Equal(t, m1, map[string]string{ 57 "name": "95eh", 58 }) 59 assert.Nil(t, err) 60 61 var names string 62 err = JsonGet[string](conn, key, &names, "name") 63 assert.Equal(t, names, "95eh") 64 assert.Nil(t, err) 65 } 66 67 func TestScan(t *testing.T) { 68 conn, err := GetConn() 69 assert.Nil(t, err) 70 defer conn.Close() 71 72 em := map[string]util.M{ 73 "service:alias:100": { 74 "scene": "world0", 75 }, 76 "service:alias:101": { 77 "scene": "novice0", 78 }, 79 } 80 for key, m := range em { 81 slc := []any{key} 82 m.ToSlice(&slc) 83 e := conn.Send(HSET, slc...) 84 assert.Nil(t, e) 85 } 86 e := conn.Flush() 87 assert.Nil(t, e) 88 err = Scan(conn, "service:alias:*", 100, func(keys []string) { 89 for i, key := range keys { 90 fmt.Println(i, key) 91 e := conn.Send(HGETALL, key) 92 assert.Nil(t, e) 93 keys[i] = key 94 } 95 e := conn.Flush() 96 assert.Nil(t, e) 97 for _, key := range keys { 98 m, e := redis.StringMap(conn.Receive()) 99 assert.Nil(t, e) 100 var um util.M 101 e = mapstructure.Decode(m, &um) 102 assert.Nil(t, e) 103 assert.EqualValues(t, um, em[key]) 104 } 105 }) 106 assert.Nil(t, err) 107 } 108 109 func TestTmp(t *testing.T) { 110 conn, err := GetConn() 111 assert.Nil(t, err) 112 defer conn.Close() 113 114 kvs := []any{"test"} 115 util.M{ 116 "name": "95eh", 117 "city": "wuhan", 118 }.ToSlice(&kvs) 119 _, e := conn.Do(HSET, kvs...) 120 fmt.Println(e) 121 }