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 package service
import "time"
type PersistenceService interface { type PersistenceService interface {
NewStore(id string, subIDs ...string) Store NewStore(id string, subIDs ...string) Store
} }
@ -10,6 +12,10 @@ type Store interface {
Reset() error Reset() error
} }
type Expirable interface {
Expiration() time.Duration
}
type RedisPersistenceConfig struct { type RedisPersistenceConfig struct {
Host string `yaml:"host" json:"host" env:"REDIS_HOST"` Host string `yaml:"host" json:"host" env:"REDIS_HOST"`
Port string `yaml:"port" json:"port" env:"REDIS_PORT"` Port string `yaml:"port" json:"port" env:"REDIS_PORT"`

View File

@ -6,6 +6,7 @@ import (
"errors" "errors"
"net" "net"
"strings" "strings"
"time"
"github.com/go-redis/redis/v8" "github.com/go-redis/redis/v8"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
@ -87,15 +88,20 @@ func (store *RedisStore) Save(val interface{}) error {
return nil return nil
} }
var expiration time.Duration
if expiringData, ok := val.(Expirable); ok {
expiration = expiringData.Expiration()
}
data, err := json.Marshal(val) data, err := json.Marshal(val)
if err != nil { if err != nil {
return err 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() _, 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 return err
} }