From 83ab00a601368e409fba44ca7fc76fc4b9628215 Mon Sep 17 00:00:00 2001 From: c9s Date: Thu, 3 Oct 2024 17:10:11 +0800 Subject: [PATCH] allow redis persistence config could be created with an existing redis client --- pkg/service/persistence.go | 10 +++++++++- pkg/service/persistence_redis.go | 19 ++++++++++++------- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/pkg/service/persistence.go b/pkg/service/persistence.go index 0cd04ac7f..ff5c55288 100644 --- a/pkg/service/persistence.go +++ b/pkg/service/persistence.go @@ -1,6 +1,10 @@ package service -import "time" +import ( + "time" + + "github.com/go-redis/redis/v8" +) type PersistenceService interface { NewStore(id string, subIDs ...string) Store @@ -22,6 +26,10 @@ type RedisPersistenceConfig struct { Password string `yaml:"password,omitempty" json:"password,omitempty" env:"REDIS_PASSWORD"` DB int `yaml:"db" json:"db" env:"REDIS_DB"` Namespace string `yaml:"namespace" json:"namespace" env:"REDIS_NAMESPACE"` + + // Redis is the redis client field + // this field is optional, only used when you want to set the redis client instance in the runtime + Redis *redis.Client } type JsonPersistenceConfig struct { diff --git a/pkg/service/persistence_redis.go b/pkg/service/persistence_redis.go index 8688c4241..fac76e453 100644 --- a/pkg/service/persistence_redis.go +++ b/pkg/service/persistence_redis.go @@ -22,13 +22,18 @@ type RedisPersistenceService struct { } func NewRedisPersistenceService(config *RedisPersistenceConfig) *RedisPersistenceService { - client := redis.NewClient(&redis.Options{ - Addr: net.JoinHostPort(config.Host, config.Port), - // Username: "", // username is only for redis 6.0 - // pragma: allowlist nextline secret - Password: config.Password, // no password set - DB: config.DB, // use default DB - }) + var client *redis.Client + if config.Redis != nil { + client = config.Redis + } else { + client = redis.NewClient(&redis.Options{ + Addr: net.JoinHostPort(config.Host, config.Port), + // Username: "", // username is only for redis 6.0 + // pragma: allowlist nextline secret + Password: config.Password, // no password set + DB: config.DB, // use default DB + }) + } return &RedisPersistenceService{ redis: client,