72 lines
1.9 KiB
Go
72 lines
1.9 KiB
Go
package redisdao
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"time"
|
|
|
|
"git.lzcwy.cn/zhengchiliu/zt-closet-backend/global"
|
|
"git.lzcwy.cn/zhengchiliu/zt-closet-backend/internal/mysqlmodel"
|
|
"git.lzcwy.cn/zhengchiliu/zt-closet-backend/internal/redismodel"
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
// userInfoTTL 用户鉴权信息缓存默认过期时间
|
|
const userInfoTTL = 24 * time.Hour
|
|
|
|
// UserInfoSet 缓存用户鉴权核心信息(含 Status,供中间件鉴权时快速读取)
|
|
func UserInfoSet(ctx context.Context, user *mysqlmodel.User, ttl time.Duration) error {
|
|
ctx, span := global.Tracer.Start(ctx, "redisdao.UserInfoSet")
|
|
defer span.End()
|
|
|
|
if ttl <= 0 {
|
|
ttl = userInfoTTL
|
|
}
|
|
data, err := json.Marshal(user)
|
|
if err != nil {
|
|
span.RecordError(err)
|
|
return err
|
|
}
|
|
key := fmt.Sprintf(redismodel.KeyUserInfo, user.ID)
|
|
if err := global.RedisEngine.Set(ctx, key, data, ttl).Err(); err != nil {
|
|
span.RecordError(err)
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// UserInfoDel 删除用户缓存(用户资料变更/注销时失效缓存)
|
|
func UserInfoDel(ctx context.Context, userID int64) error {
|
|
ctx, span := global.Tracer.Start(ctx, "redisdao.UserInfoDel")
|
|
defer span.End()
|
|
|
|
key := fmt.Sprintf(redismodel.KeyUserInfo, userID)
|
|
if err := global.RedisEngine.Del(ctx, key).Err(); err != nil {
|
|
span.RecordError(err)
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// UserInfoGet 读取缓存中的用户鉴权核心信息,未命中返回 redis.Nil
|
|
func UserInfoGet(ctx context.Context, userID int64) (*mysqlmodel.User, error) {
|
|
ctx, span := global.Tracer.Start(ctx, "redisdao.UserInfoGet")
|
|
defer span.End()
|
|
|
|
key := fmt.Sprintf(redismodel.KeyUserInfo, userID)
|
|
data, err := global.RedisEngine.Get(ctx, key).Bytes()
|
|
if err != nil {
|
|
if err != redis.Nil {
|
|
span.RecordError(err)
|
|
}
|
|
return nil, err
|
|
}
|
|
var user mysqlmodel.User
|
|
if err := json.Unmarshal(data, &user); err != nil {
|
|
span.RecordError(err)
|
|
return nil, err
|
|
}
|
|
return &user, nil
|
|
}
|