service: add redis namespace support

This commit is contained in:
c9s 2023-01-05 19:07:15 +08:00
parent f03cc3c5de
commit 5765969573
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
2 changed files with 19 additions and 8 deletions

View File

@ -11,10 +11,11 @@ type Store interface {
}
type RedisPersistenceConfig struct {
Host string `yaml:"host" json:"host" env:"REDIS_HOST"`
Port string `yaml:"port" json:"port" env:"REDIS_PORT"`
Password string `yaml:"password,omitempty" json:"password,omitempty" env:"REDIS_PASSWORD"`
DB int `yaml:"db" json:"db" env:"REDIS_DB"`
Host string `yaml:"host" json:"host" env:"REDIS_HOST"`
Port string `yaml:"port" json:"port" env:"REDIS_PORT"`
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"`
}
type JsonPersistenceConfig struct {

View File

@ -11,8 +11,13 @@ import (
log "github.com/sirupsen/logrus"
)
var redisLogger = log.WithFields(log.Fields{
"persistence": "redis",
})
type RedisPersistenceService struct {
redis *redis.Client
redis *redis.Client
config *RedisPersistenceConfig
}
func NewRedisPersistenceService(config *RedisPersistenceConfig) *RedisPersistenceService {
@ -25,7 +30,8 @@ func NewRedisPersistenceService(config *RedisPersistenceConfig) *RedisPersistenc
})
return &RedisPersistenceService{
redis: client,
redis: client,
config: config,
}
}
@ -34,6 +40,10 @@ func (s *RedisPersistenceService) NewStore(id string, subIDs ...string) Store {
id += ":" + strings.Join(subIDs, ":")
}
if s.config != nil && s.config.Namespace != "" {
id = s.config.Namespace + ":" + id
}
return &RedisStore{
redis: s.redis,
ID: id,
@ -54,7 +64,7 @@ func (store *RedisStore) Load(val interface{}) error {
cmd := store.redis.Get(context.Background(), store.ID)
data, err := cmd.Result()
log.Debugf("[redis] get key %q, data = %s", store.ID, string(data))
redisLogger.Debugf("[redis] get key %q, data = %s", store.ID, string(data))
if err != nil {
if err == redis.Nil {
@ -85,7 +95,7 @@ func (store *RedisStore) Save(val interface{}) error {
cmd := store.redis.Set(context.Background(), store.ID, data, 0)
_, err = cmd.Result()
log.Debugf("[redis] set key %q, data = %s", store.ID, string(data))
redisLogger.Debugf("[redis] set key %q, data = %s", store.ID, string(data))
return err
}