You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
1.6 KiB
Go

package redistable
import (
"context"
"joybuywork/internal/app"
"joybuywork/internal/consts"
"joybuywork/internal/consts/ckey"
"fmt"
"time"
)
type RedisTable struct {
Ctx context.Context
tableName string //表名称
row map[string]string //行数据
exp time.Duration
}
// Init 初始化结构体
func (t *RedisTable) Init(ctx context.Context, tableName string, opts ...Option) {
t.Ctx = ctx
t.tableName = ckey.RedisTableKey(tableName)
t.row = make(map[string]string)
t.exp = consts.TimeWeek
for _, opt := range opts {
opt(t)
}
}
// GetTableName 获取表名
func (t *RedisTable) GetTableName() string {
return t.tableName
}
// AddField 添加字段
func (t *RedisTable) AddField(field string, val interface{}) *RedisTable {
t.row[field] = fmt.Sprint(val)
return t
}
// GetRow 获取数据列
func (t *RedisTable) GetRow() map[string]string {
if len(t.row) == 0 {
val := app.Redis.Cache.HGetAll(t.Ctx, t.tableName).Val()
if val != nil {
t.row = val
}
}
return t.row
}
// DropTable 清空表数据
func (t *RedisTable) DropTable() {
app.Redis.Cache.Del(t.Ctx, t.tableName)
}
// Set 清空表数据
func (t *RedisTable) Set() error {
if len(t.row) == 0 {
return nil
}
defer func() { //每次设置的时候,重新设置过期时间
app.Redis.Cache.Expire(t.Ctx, t.tableName, t.exp)
}()
return app.Redis.Cache.HMSet(t.Ctx, t.tableName, t.row).Err()
}
// IncrBy 步进处理
func (t *RedisTable) IncrBy(field string, incr int64) int64 {
num := app.Redis.Cache.HIncrBy(t.Ctx, t.GetTableName(), field, incr).Val()
t.AddField(field, num)
return num
}