2023-10-27 17:41:45 +08:00
|
|
|
package rdm
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
2024-03-02 19:08:19 +08:00
|
|
|
"mayfly-go/pkg/errorx"
|
2023-10-27 17:41:45 +08:00
|
|
|
"mayfly-go/pkg/logx"
|
|
|
|
|
|
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// redis连接信息
|
|
|
|
|
type RedisConn struct {
|
|
|
|
|
Id string
|
|
|
|
|
Info *RedisInfo
|
|
|
|
|
|
|
|
|
|
Cli *redis.Client
|
|
|
|
|
ClusterCli *redis.ClusterClient
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 获取命令执行接口的具体实现
|
|
|
|
|
func (r *RedisConn) GetCmdable() redis.Cmdable {
|
|
|
|
|
redisMode := r.Info.Mode
|
|
|
|
|
if redisMode == "" || redisMode == StandaloneMode || r.Info.Mode == SentinelMode {
|
|
|
|
|
return r.Cli
|
|
|
|
|
}
|
|
|
|
|
if redisMode == ClusterMode {
|
|
|
|
|
return r.ClusterCli
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (r *RedisConn) Scan(cursor uint64, match string, count int64) ([]string, uint64, error) {
|
|
|
|
|
return r.GetCmdable().Scan(context.Background(), cursor, match, count).Result()
|
|
|
|
|
}
|
|
|
|
|
|
2024-03-02 19:08:19 +08:00
|
|
|
// 执行redis命令
|
|
|
|
|
// 如: SET str value命令则args为['SET', 'str', 'val']
|
|
|
|
|
func (r *RedisConn) RunCmd(ctx context.Context, args ...any) (any, error) {
|
|
|
|
|
redisMode := r.Info.Mode
|
|
|
|
|
if redisMode == "" || redisMode == StandaloneMode || r.Info.Mode == SentinelMode {
|
|
|
|
|
return r.Cli.Do(ctx, args...).Result()
|
|
|
|
|
}
|
|
|
|
|
if redisMode == ClusterMode {
|
|
|
|
|
return r.ClusterCli.Do(ctx, args...).Result()
|
|
|
|
|
}
|
|
|
|
|
return nil, errorx.NewBiz("redis mode error")
|
|
|
|
|
}
|
|
|
|
|
|
2023-10-27 17:41:45 +08:00
|
|
|
func (r *RedisConn) Close() {
|
|
|
|
|
mode := r.Info.Mode
|
|
|
|
|
if mode == StandaloneMode || mode == SentinelMode {
|
|
|
|
|
if err := r.Cli.Close(); err != nil {
|
2024-11-20 22:43:53 +08:00
|
|
|
logx.Errorf("close redis standalone instance [%s] connection failed: %s", r.Id, err.Error())
|
2023-10-27 17:41:45 +08:00
|
|
|
}
|
|
|
|
|
r.Cli = nil
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if mode == ClusterMode {
|
|
|
|
|
if err := r.ClusterCli.Close(); err != nil {
|
2024-11-20 22:43:53 +08:00
|
|
|
logx.Errorf("close redis cluster instance [%s] connection failed: %s", r.Id, err.Error())
|
2023-10-27 17:41:45 +08:00
|
|
|
}
|
|
|
|
|
r.ClusterCli = nil
|
|
|
|
|
}
|
|
|
|
|
}
|