Add sentinel connection support via redis-url

This commit is contained in:
Ken Hibino 2022-05-04 06:47:08 -07:00
parent 6dbc580738
commit 0527b6c483
2 changed files with 33 additions and 6 deletions

View File

@ -83,23 +83,31 @@ func parseFlags(progname string, args []string) (cfg *Config, output string, err
return &conf, buf.String(), nil return &conf, buf.String(), nil
} }
// TODO: Write test and refactor this code. // TODO: Refactor this code!
func makeRedisConnOpt(cfg *Config) (asynq.RedisConnOpt, error) { func makeRedisConnOpt(cfg *Config) (asynq.RedisConnOpt, error) {
var opts redis.UniversalOptions var opts redis.UniversalOptions
sentinel := false
if cfg.RedisClusterNodes != "" { if cfg.RedisClusterNodes != "" {
opts.Addrs = strings.Split(cfg.RedisClusterNodes, ",") opts.Addrs = strings.Split(cfg.RedisClusterNodes, ",")
opts.Password = cfg.RedisPassword opts.Password = cfg.RedisPassword
} else { } else {
if cfg.RedisURL != "" { if cfg.RedisURL != "" {
res, err := redis.ParseURL(cfg.RedisURL) res, err := asynq.ParseRedisURI(cfg.RedisURL)
if err != nil { if err != nil {
return nil, err return nil, err
} }
opts.Addrs = append(opts.Addrs, res.Addr) switch v := res.(type) {
opts.DB = res.DB case asynq.RedisClientOpt:
opts.Password = res.Password opts.Addrs = append(opts.Addrs, v.Addr)
opts.DB = v.DB
opts.Password = v.Password
case asynq.RedisFailoverClientOpt:
opts.Addrs = append(opts.Addrs, v.SentinelAddrs...)
opts.SentinelPassword = v.SentinelPassword
opts.MasterName = v.MasterName
sentinel = true
}
} else { } else {
opts.Addrs = []string{cfg.RedisAddr} opts.Addrs = []string{cfg.RedisAddr}
opts.DB = cfg.RedisDB opts.DB = cfg.RedisDB
@ -124,6 +132,14 @@ func makeRedisConnOpt(cfg *Config) (asynq.RedisConnOpt, error) {
TLSConfig: opts.TLSConfig, TLSConfig: opts.TLSConfig,
}, nil }, nil
} }
if sentinel {
return asynq.RedisFailoverClientOpt{
MasterName: opts.MasterName,
SentinelAddrs: opts.Addrs,
SentinelPassword: opts.SentinelPassword,
TLSConfig: opts.TLSConfig,
}, nil
}
return asynq.RedisClientOpt{ return asynq.RedisClientOpt{
Addr: opts.Addrs[0], Addr: opts.Addrs[0],
DB: opts.DB, DB: opts.DB,

View File

@ -97,6 +97,17 @@ func TestMakeRedisConnOpt(t *testing.T) {
Password: "bar", Password: "bar",
}, },
}, },
{
desc: "With redis-sentinel URL",
cfg: &Config{
RedisURL: "redis-sentinel://:secretpassword@localhost:5000,localhost:5001,localhost:5002?master=mymaster",
},
want: asynq.RedisFailoverClientOpt{
MasterName: "mymaster",
SentinelAddrs: []string{
"localhost:5000", "localhost:5001", "localhost:5002"},
},
},
{ {
desc: "With cluster nodes", desc: "With cluster nodes",
cfg: &Config{ cfg: &Config{