1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
key.go 2.55 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2022-06-01 16:22 . init
package pool
import (
"context"
"time"
"github.com/go-redis/redis/v8"
)
//Del 删除key
func (c *Client) Del(ctx context.Context, keys ...string) (int64, error) {
client, cErr := getClusterClient(c)
if cErr != nil {
return 0, cErr
}
slotsMap := make(map[int][]string)
for _, k := range keys {
slot := Slot(k)
if _, ok := slotsMap[slot]; !ok {
slotsMap[slot] = make([]string, 0)
}
slotsMap[slot] = append(slotsMap[slot], k)
}
cmds, err := client.Pipelined(ctx, func(pipe redis.Pipeliner) error {
for _, k := range slotsMap {
pipe.Del(ctx, k...)
}
return nil
})
if err != nil {
return 0, err
}
var res int64
for _, cmd := range cmds {
r, err := cmd.(*redis.IntCmd).Result()
if err != nil {
return res, err
}
res += r
}
return res, err
}
//Keys 查询是否存在key
func (c *Client) Keys(ctx context.Context, key string) ([]string, error) {
client, cErr := getClusterClient(c)
if cErr != nil {
return nil, cErr
}
keys := make([]string, 0)
err := client.ForEachMaster(ctx, func(ctx context.Context, client *redis.Client) error {
res, err := client.Keys(ctx, key).Result()
if err != nil {
return err
}
keys = append(keys, res...)
return err
})
return keys, err
}
//Expire 设置过期时间
func (c *Client) Expire(ctx context.Context, key string, expiration time.Duration) (bool, error) {
client, cErr := getClusterClient(c)
if cErr != nil {
return false, cErr
}
res, err := client.Expire(ctx, key, expiration).Result()
return res, err
}
//MExpireReq 批量设置过期时间参数
type MExpireReq struct {
Key string
Expiration time.Duration
}
//MExpire 批量设置过期时间
func (c *Client) MExpire(ctx context.Context, reqs []*MExpireReq) (bool, error) {
client, cErr := getClusterClient(c)
if cErr != nil {
return false, cErr
}
cmds, err := client.Pipelined(ctx, func(pipe redis.Pipeliner) error {
for _, req := range reqs {
pipe.Expire(ctx, req.Key, req.Expiration)
}
return nil
})
res := true
err = nil
for _, cmd := range cmds {
res, err = cmd.(*redis.BoolCmd).Result()
if err != nil {
break
}
}
return res, err
}
//TTL 查询TTL
func (c *Client) TTL(ctx context.Context, key string) (time.Duration, error) {
client, cErr := getClusterClient(c)
if cErr != nil {
return -2, cErr
}
return client.TTL(ctx, key).Result()
}
//Exists 查询key是否存在
func (c *Client) Exists(ctx context.Context, key ...string) (int64, error) {
client, cErr := getClusterClient(c)
if cErr != nil {
return -2, cErr
}
return client.Exists(ctx, key...).Result()
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.20.107

搜索帮助