bbgo_origin/pkg/service/persistence_redis.go

112 lines
2.3 KiB
Go
Raw Normal View History

package service
import (
"context"
"encoding/json"
"errors"
"net"
"strings"
2023-03-03 07:42:29 +00:00
"time"
"github.com/go-redis/redis/v8"
log "github.com/sirupsen/logrus"
)
2023-01-05 11:07:15 +00:00
var redisLogger = log.WithFields(log.Fields{
"persistence": "redis",
})
type RedisPersistenceService struct {
2023-01-05 11:07:15 +00:00
redis *redis.Client
config *RedisPersistenceConfig
}
2021-02-20 17:01:39 +00:00
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
2022-06-17 07:04:23 +00:00
// pragma: allowlist nextline secret
Password: config.Password, // no password set
DB: config.DB, // use default DB
})
return &RedisPersistenceService{
2023-01-05 11:07:15 +00:00
redis: client,
config: config,
}
}
2021-02-20 17:01:39 +00:00
func (s *RedisPersistenceService) NewStore(id string, subIDs ...string) Store {
if len(subIDs) > 0 {
id += ":" + strings.Join(subIDs, ":")
}
2023-01-05 11:07:15 +00:00
if s.config != nil && s.config.Namespace != "" {
id = s.config.Namespace + ":" + id
}
return &RedisStore{
redis: s.redis,
ID: id,
}
}
type RedisStore struct {
redis *redis.Client
ID string
}
func (store *RedisStore) Load(val interface{}) error {
if store.redis == nil {
return errors.New("can not load from redis, possible cause: redis persistence is not configured, or you are trying to use redis in back-test")
}
cmd := store.redis.Get(context.Background(), store.ID)
data, err := cmd.Result()
2023-01-05 11:07:15 +00:00
redisLogger.Debugf("[redis] get key %q, data = %s", store.ID, string(data))
if err != nil {
if err == redis.Nil {
return ErrPersistenceNotExists
}
return err
}
2022-06-04 17:48:56 +00:00
// skip null data
if len(data) == 0 || data == "null" {
return ErrPersistenceNotExists
}
return json.Unmarshal([]byte(data), val)
}
func (store *RedisStore) Save(val interface{}) error {
if val == nil {
return nil
}
2023-03-03 07:42:29 +00:00
var expiration time.Duration
if expiringData, ok := val.(Expirable); ok {
expiration = expiringData.Expiration()
}
data, err := json.Marshal(val)
if err != nil {
return err
}
2023-03-03 07:42:29 +00:00
cmd := store.redis.Set(context.Background(), store.ID, data, expiration)
_, err = cmd.Result()
2023-03-03 07:42:29 +00:00
redisLogger.Debugf("[redis] set key %q, data = %s, expiration = %s", store.ID, string(data), expiration)
return err
}
func (store *RedisStore) Reset() error {
_, err := store.redis.Del(context.Background(), store.ID).Result()
return err
2023-03-03 07:42:29 +00:00
}