FEATURE: save expiring data to redis

This commit is contained in:
gx578007 2023-03-03 15:42:29 +08:00
parent 16fe416520
commit 4deefefe0f
2 changed files with 16 additions and 4 deletions

View File

@ -1,5 +1,7 @@
package service
import "time"
type PersistenceService interface {
NewStore(id string, subIDs ...string) Store
}
@ -10,6 +12,10 @@ type Store interface {
Reset() error
}
type Expirable interface {
Expiration() time.Duration
}
type RedisPersistenceConfig struct {
Host string `yaml:"host" json:"host" env:"REDIS_HOST"`
Port string `yaml:"port" json:"port" env:"REDIS_PORT"`
@ -20,4 +26,4 @@ type RedisPersistenceConfig struct {
type JsonPersistenceConfig struct {
Directory string `yaml:"directory" json:"directory"`
}
}

View File

@ -6,6 +6,7 @@ import (
"errors"
"net"
"strings"
"time"
"github.com/go-redis/redis/v8"
log "github.com/sirupsen/logrus"
@ -87,15 +88,20 @@ func (store *RedisStore) Save(val interface{}) error {
return nil
}
var expiration time.Duration
if expiringData, ok := val.(Expirable); ok {
expiration = expiringData.Expiration()
}
data, err := json.Marshal(val)
if err != nil {
return err
}
cmd := store.redis.Set(context.Background(), store.ID, data, 0)
cmd := store.redis.Set(context.Background(), store.ID, data, expiration)
_, err = cmd.Result()
redisLogger.Debugf("[redis] set key %q, data = %s", store.ID, string(data))
redisLogger.Debugf("[redis] set key %q, data = %s, expiration = %s", store.ID, string(data), expiration)
return err
}
@ -103,4 +109,4 @@ func (store *RedisStore) Save(val interface{}) error {
func (store *RedisStore) Reset() error {
_, err := store.redis.Del(context.Background(), store.ID).Result()
return err
}
}