gitee.com/h79/goutils@v1.22.10/dao/redis/pool/key.go (about) 1 package pool 2 3 import ( 4 "context" 5 "time" 6 7 "github.com/go-redis/redis/v8" 8 ) 9 10 //Del 删除key 11 func (c *Client) Del(ctx context.Context, keys ...string) (int64, error) { 12 client, cErr := getClusterClient(c) 13 14 if cErr != nil { 15 return 0, cErr 16 } 17 18 slotsMap := make(map[int][]string) 19 for _, k := range keys { 20 slot := Slot(k) 21 if _, ok := slotsMap[slot]; !ok { 22 slotsMap[slot] = make([]string, 0) 23 } 24 slotsMap[slot] = append(slotsMap[slot], k) 25 } 26 27 cmds, err := client.Pipelined(ctx, func(pipe redis.Pipeliner) error { 28 for _, k := range slotsMap { 29 pipe.Del(ctx, k...) 30 } 31 return nil 32 }) 33 34 if err != nil { 35 return 0, err 36 } 37 38 var res int64 39 for _, cmd := range cmds { 40 r, err := cmd.(*redis.IntCmd).Result() 41 if err != nil { 42 return res, err 43 } 44 res += r 45 } 46 47 return res, err 48 } 49 50 //Keys 查询是否存在key 51 func (c *Client) Keys(ctx context.Context, key string) ([]string, error) { 52 client, cErr := getClusterClient(c) 53 54 if cErr != nil { 55 return nil, cErr 56 } 57 58 keys := make([]string, 0) 59 60 err := client.ForEachMaster(ctx, func(ctx context.Context, client *redis.Client) error { 61 res, err := client.Keys(ctx, key).Result() 62 if err != nil { 63 return err 64 } 65 keys = append(keys, res...) 66 return err 67 }) 68 69 return keys, err 70 } 71 72 //Expire 设置过期时间 73 func (c *Client) Expire(ctx context.Context, key string, expiration time.Duration) (bool, error) { 74 client, cErr := getClusterClient(c) 75 76 if cErr != nil { 77 return false, cErr 78 } 79 80 res, err := client.Expire(ctx, key, expiration).Result() 81 82 return res, err 83 } 84 85 //MExpireReq 批量设置过期时间参数 86 type MExpireReq struct { 87 Key string 88 Expiration time.Duration 89 } 90 91 //MExpire 批量设置过期时间 92 func (c *Client) MExpire(ctx context.Context, reqs []*MExpireReq) (bool, error) { 93 client, cErr := getClusterClient(c) 94 95 if cErr != nil { 96 return false, cErr 97 } 98 99 cmds, err := client.Pipelined(ctx, func(pipe redis.Pipeliner) error { 100 for _, req := range reqs { 101 pipe.Expire(ctx, req.Key, req.Expiration) 102 } 103 return nil 104 }) 105 106 res := true 107 err = nil 108 for _, cmd := range cmds { 109 res, err = cmd.(*redis.BoolCmd).Result() 110 if err != nil { 111 break 112 } 113 } 114 115 return res, err 116 } 117 118 //TTL 查询TTL 119 func (c *Client) TTL(ctx context.Context, key string) (time.Duration, error) { 120 client, cErr := getClusterClient(c) 121 122 if cErr != nil { 123 return -2, cErr 124 } 125 126 return client.TTL(ctx, key).Result() 127 } 128 129 //Exists 查询key是否存在 130 func (c *Client) Exists(ctx context.Context, key ...string) (int64, error) { 131 client, cErr := getClusterClient(c) 132 133 if cErr != nil { 134 return -2, cErr 135 } 136 137 return client.Exists(ctx, key...).Result() 138 }