diff --git a/cache/cache.go b/cache/cache.go index 0bef532..4c545b3 100644 --- a/cache/cache.go +++ b/cache/cache.go @@ -13,14 +13,14 @@ type Cache interface { type CfgCache struct { *ristretto.Config - Type string - RedisUrl string + Type string + Redis *RedisConfig } func NewCache(cfg *CfgCache) Cache { var cache Cache - if cfg.Type == "redis" && cfg.RedisUrl != "" { - cache = NewRedisCache(cfg.RedisUrl) + if cfg.Type == "redis" && cfg.Redis != nil { + cache = NewRedisCache(cfg.Redis) } else { if cfg.Config == nil { cache, _ = NewRistrettoCacheDefault() diff --git a/cache/cache_test.go b/cache/cache_test.go index 7c30b67..d9bbe51 100644 --- a/cache/cache_test.go +++ b/cache/cache_test.go @@ -16,8 +16,10 @@ func TestCache(t *testing.T) { Type: "ristretto", }}, {"Redis", &cache.CfgCache{ - Type: "ristretto", - RedisUrl: "localhost:6379", + Type: "ristretto", + Redis: &cache.RedisConfig{ + Addresses: "localhost:6379", + }, }}, } @@ -158,8 +160,10 @@ func TestDelKey(t *testing.T) { Type: "ristretto", }}, {"Redis", &cache.CfgCache{ - Type: "ristretto", - RedisUrl: "localhost:6379", + Type: "ristretto", + Redis: &cache.RedisConfig{ + Addresses: "localhost:6379", + }, }}, } for _, ct := range cacheTypes { diff --git a/cache/redis_cache.go b/cache/redis_cache.go index afb76ef..d72cfcb 100644 --- a/cache/redis_cache.go +++ b/cache/redis_cache.go @@ -5,18 +5,61 @@ import ( "encoding/json" "errors" "fmt" + "strings" "time" "github.com/redis/go-redis/v9" ) +// RedisConfig contains all configuration of redis +type RedisConfig struct { + Addresses string + MasterName string + DBNumber int + Username string + Password string + SentinelUsername string + SentinelPassword string + Prefix string + Separator string + ReadTimeout time.Duration + WriteTimeout time.Duration + RouteRandomly bool + ReplicaOnly bool +} + type RedisCache struct { - client *redis.Client + client redis.UniversalClient } -func NewRedisCache(redisURL string) *RedisCache { - client := redis.NewClient(&redis.Options{ - Addr: redisURL, +func NewRedisCache(cfg *RedisConfig) *RedisCache { + addrs := strings.Split(cfg.Addresses, ",") + if cfg.MasterName != "" { + client := redis.NewFailoverClusterClient(&redis.FailoverOptions{ + MasterName: cfg.MasterName, + SentinelAddrs: addrs, + DB: cfg.DBNumber, + Username: cfg.Username, + Password: cfg.Password, + SentinelUsername: cfg.SentinelUsername, + SentinelPassword: cfg.SentinelPassword, + ReadTimeout: cfg.ReadTimeout, + WriteTimeout: cfg.WriteTimeout, + RouteRandomly: cfg.RouteRandomly, + ReplicaOnly: cfg.ReplicaOnly, + }) + return &RedisCache{client: client} + } + client := redis.NewUniversalClient(&redis.UniversalOptions{ + Addrs: addrs, + MasterName: cfg.MasterName, + DB: cfg.DBNumber, + Username: cfg.Username, + Password: cfg.Password, + SentinelUsername: cfg.SentinelUsername, + SentinelPassword: cfg.SentinelPassword, + ReadTimeout: cfg.ReadTimeout, + WriteTimeout: cfg.WriteTimeout, }) return &RedisCache{client: client} }