Add support for Redis Universal Client

This commit is contained in:
Juan Calderon-Perez
2023-04-09 21:04:52 -07:00
parent 7e6ede5392
commit 22e48de898
3 changed files with 81 additions and 74 deletions

View File

@@ -32,28 +32,23 @@ type Config struct {
// Optional. Default is 0 // Optional. Default is 0
Database int Database int
// URL the standard format redis url to parse all other options. If this is set all other config options, Host, Port, Username, Password, Database have no effect. // URL standard format Redis URL. If this is set all other config options, Host, Port, Username, Password, Database have no effect.
// //
// Example: redis://<user>:<pass>@localhost:6379/<db> // Example: redis://<user>:<pass>@localhost:6379/<db>
// Optional. Default is "" // Optional. Default is ""
URL string URL string
// EnableFailover to use redis FailoverClient with Sentinel instead of the standard redis Client // Either a single address or a seed list of host:port addresses, this enables FailoverClient and ClusterClient
//
// Optional. Default is false
EnableFailover bool
// SentinelHosts where the Redis Sentinel is hosted
// //
// Optional. Default is []string{} // Optional. Default is []string{}
SentinelHosts []string Addrs []string
// MasterName is the sentinel master's name // MasterName is the sentinel master's name
// //
// Optional. Default is "" // Optional. Default is ""
MasterName string MasterName string
// ClientName will execute the `CLIENT SETNAME ClientName` command for each sentinel conn. // ClientName will execute the `CLIENT SETNAME ClientName` command for each conn.
// //
// Optional. Default is "" // Optional. Default is ""
ClientName string ClientName string
@@ -82,31 +77,24 @@ type Config struct {
// //
// Optional. Default is 10 connections per every available CPU as reported by runtime.GOMAXPROCS. // Optional. Default is 10 connections per every available CPU as reported by runtime.GOMAXPROCS.
PoolSize int PoolSize int
////////////////////////////////////
// Adaptor related config options //
////////////////////////////////////
// https://pkg.go.dev/github.com/go-redis/redis/v8#Options
} }
// ConfigDefault is the default config // ConfigDefault is the default config
var ConfigDefault = Config{ var ConfigDefault = Config{
Host: "127.0.0.1", Host: "127.0.0.1",
Port: 6379, Port: 6379,
Username: "", Username: "",
Password: "", Password: "",
URL: "", URL: "",
Database: 0, Database: 0,
Reset: false, Reset: false,
TLSConfig: nil, TLSConfig: nil,
PoolSize: 10 * runtime.GOMAXPROCS(0), PoolSize: 10 * runtime.GOMAXPROCS(0),
EnableFailover: false, Addrs: []string{},
MasterName: "", MasterName: "",
SentinelHosts: []string{}, ClientName: "",
ClientName: "", SentinelUsername: "",
SentinelUsername: "", SentinelPassword: "",
SentinelPassword: "",
} }
// Helper function to set default values // Helper function to set default values

View File

@@ -10,7 +10,7 @@ import (
// Storage interface that is implemented by storage providers // Storage interface that is implemented by storage providers
type Storage struct { type Storage struct {
db *redis.Client db redis.UniversalClient
} }
// New creates a new redis storage // New creates a new redis storage
@@ -18,42 +18,39 @@ func New(config ...Config) *Storage {
// Set default config // Set default config
cfg := configDefault(config...) cfg := configDefault(config...)
// Create new redis client // Create new redis universal client
var db *redis.Client var db redis.UniversalClient
if cfg.URL != "" && !cfg.EnableFailover { // Parse the URL and update config values accordingly
if cfg.URL != "" {
options, err := redis.ParseURL(cfg.URL) options, err := redis.ParseURL(cfg.URL)
if err != nil { if err != nil {
panic(err) panic(err)
} }
options.TLSConfig = cfg.TLSConfig // Update the config values with the parsed URL values
options.PoolSize = cfg.PoolSize cfg.Username = options.Username
db = redis.NewClient(options) cfg.Password = options.Password
} else if cfg.EnableFailover { cfg.Database = options.DB
db = redis.NewFailoverClient(&redis.FailoverOptions{ cfg.Addrs = []string{options.Addr}
MasterName: cfg.MasterName, } else if len(cfg.Addrs) == 0 {
SentinelAddrs: cfg.SentinelHosts, // Fallback to Host and Port values if Addrs is empty
ClientName: cfg.ClientName, cfg.Addrs = []string{fmt.Sprintf("%s:%d", cfg.Host, cfg.Port)}
SentinelUsername: cfg.SentinelUsername,
SentinelPassword: cfg.SentinelPassword,
DB: cfg.Database,
Password: cfg.Password,
TLSConfig: cfg.TLSConfig,
PoolSize: cfg.PoolSize,
})
} else {
db = redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%d", cfg.Host, cfg.Port),
DB: cfg.Database,
Username: cfg.Username,
Password: cfg.Password,
TLSConfig: cfg.TLSConfig,
PoolSize: cfg.PoolSize,
})
} }
db = redis.NewUniversalClient(&redis.UniversalOptions{
Addrs: cfg.Addrs,
MasterName: cfg.MasterName,
ClientName: cfg.ClientName,
SentinelUsername: cfg.SentinelUsername,
SentinelPassword: cfg.SentinelPassword,
DB: cfg.Database,
Username: cfg.Username,
Password: cfg.Password,
TLSConfig: cfg.TLSConfig,
PoolSize: cfg.PoolSize,
})
// Test connection // Test connection
if err := db.Ping(context.Background()).Err(); err != nil { if err := db.Ping(context.Background()).Err(); err != nil {
panic(err) panic(err)
@@ -72,6 +69,8 @@ func New(config ...Config) *Storage {
} }
} }
// ...
// Get value by key // Get value by key
func (s *Storage) Get(key string) ([]byte, error) { func (s *Storage) Get(key string) ([]byte, error) {
if len(key) <= 0 { if len(key) <= 0 {
@@ -86,7 +85,6 @@ func (s *Storage) Get(key string) ([]byte, error) {
// Set key with value // Set key with value
func (s *Storage) Set(key string, val []byte, exp time.Duration) error { func (s *Storage) Set(key string, val []byte, exp time.Duration) error {
// Ain't Nobody Got Time For That
if len(key) <= 0 || len(val) <= 0 { if len(key) <= 0 || len(val) <= 0 {
return nil return nil
} }
@@ -95,7 +93,6 @@ func (s *Storage) Set(key string, val []byte, exp time.Duration) error {
// Delete key by key // Delete key by key
func (s *Storage) Delete(key string) error { func (s *Storage) Delete(key string) error {
// Ain't Nobody Got Time For That
if len(key) <= 0 { if len(key) <= 0 {
return nil return nil
} }
@@ -113,6 +110,6 @@ func (s *Storage) Close() error {
} }
// Return database client // Return database client
func (s *Storage) Conn() *redis.Client { func (s *Storage) Conn() redis.UniversalClient {
return s.db return s.db
} }

View File

@@ -192,14 +192,10 @@ func Test_Redis_Initalize_WithURL_TLS(t *testing.T) {
utils.AssertEqual(t, nil, testStoreUrl.Close()) utils.AssertEqual(t, nil, testStoreUrl.Close())
} }
func Test_Redis_Sentinel(t *testing.T) { func Test_Redis_Universal(t *testing.T) {
testStoreSentinel := New(Config{ // This should failover and create a Single Node connection.
EnableFailover: true, testStoreUniversal := New(Config{
MasterName: "", Addrs: []string{"localhost:6379"},
SentinelHosts: []string{"localhost:6379"},
ClientName: "",
SentinelUsername: "",
SentinelPassword: "",
}) })
var ( var (
@@ -207,15 +203,41 @@ func Test_Redis_Sentinel(t *testing.T) {
val = []byte("wayne") val = []byte("wayne")
) )
err := testStoreSentinel.Set(key, val, 0) err := testStoreUniversal.Set(key, val, 0)
utils.AssertEqual(t, nil, err) utils.AssertEqual(t, nil, err)
result, err := testStoreSentinel.Get(key) result, err := testStoreUniversal.Get(key)
utils.AssertEqual(t, nil, err) utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, val, result) utils.AssertEqual(t, val, result)
err = testStoreSentinel.Delete(key) err = testStoreUniversal.Delete(key)
utils.AssertEqual(t, nil, err) utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, nil, testStoreSentinel.Close()) utils.AssertEqual(t, nil, testStoreUniversal.Close())
}
func Test_Redis_Universal_With_URL(t *testing.T) {
// This should failover to creating a regular *redis.Client
// The URL should get ignored since EnableUniversalClient is enabled
testStoreUniversal := New(Config{
URL: "",
Addrs: []string{"localhost:6379"},
})
var (
key = "bruce"
val = []byte("wayne")
)
err := testStoreUniversal.Set(key, val, 0)
utils.AssertEqual(t, nil, err)
result, err := testStoreUniversal.Get(key)
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, val, result)
err = testStoreUniversal.Delete(key)
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, nil, testStoreUniversal.Close())
} }