hpds_jkw_web/internal/middleware/nosql.go

43 lines
927 B
Go
Raw Permalink Normal View History

2023-01-06 10:09:23 +08:00
package middleware
import (
"context"
"errors"
"github.com/go-redis/redis"
"hpds-iot-web/model"
"time"
"go.uber.org/zap"
)
type NoSql interface {
Save(ctx context.Context, key string, value []byte, expires time.Duration) (err error)
Get(ctx context.Context, key string) (data interface{}, err error)
}
// noSql 接口实现类
type noSql struct {
rdb *redis.Client
logger *zap.Logger
}
func NewNoSql(logger *zap.Logger) NoSql {
return &noSql{
rdb: model.Redis,
logger: logger,
}
}
func (ns *noSql) Save(ctx context.Context, key string, value []byte, expires time.Duration) (err error) {
return ns.rdb.Set(key, value, expires).Err()
}
func (ns *noSql) Get(ctx context.Context, key string) (data interface{}, err error) {
data, err = ns.rdb.Get(key).Result()
if err == redis.Nil {
return nil, errors.New("键" + key + "不存在")
} else if err != nil {
return nil, err
}
return data, nil
}