allow redis persistence config could be created with an existing redis client

This commit is contained in:
c9s 2024-10-03 17:10:11 +08:00
parent a548596c16
commit 83ab00a601
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
2 changed files with 21 additions and 8 deletions

View File

@ -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 {

View File

@ -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,