picgo/data/user.go

63 lines
1.7 KiB
Go
Raw Normal View History

package data
import (
"context"
"picgo/corelib"
"picgo/model"
"time"
)
// SysUserSelectByUsername 通过用户名查询用户
func SysUserSelectByUsername(userName string) (model.SysUser, error) {
var (
err error
user model.SysUser
)
if user, err = SysUserGetCacheByUsername(userName); err == nil {
corelib.Logger.Infoln("SysUserSelectByUsername 从缓存获取用户信息成功: ", user.Username)
return user, nil
} else {
corelib.Logger.Infoln("SysUserSelectByUsername 从缓存获取用户信息失败: ", err)
}
if err = corelib.DbMysql.Model(model.SysUser{Username: userName}).First(&user).Error; err != nil {
corelib.Logger.Infoln("SysUserSelectByUsername 数据库中查询用户信息失败: ", err)
return user, err
}
if err = SysUserSetCacheByUsername(user); err != nil {
corelib.Logger.Infoln("SysUserSelectByUsername 缓存用户信息失败: ", err)
return user, nil
}
return user, nil
}
func SysUserSetCacheByUsername(user model.SysUser) error {
var (
jsonData []byte
err error
)
if jsonData, err = corelib.JsonMarshal(user); err != nil {
return err
}
key := corelib.UserKey + user.Username
if err = corelib.RdbClient.Set(context.Background(), key, string(jsonData), 5*time.Minute).Err(); err != nil {
return err
}
return nil
}
// SysUserGetCacheByUsername redis获取用户信息
func SysUserGetCacheByUsername(userName string) (model.SysUser, error) {
var (
err error
user model.SysUser
userCache string
)
if userCache, err = corelib.RdbClient.Get(context.Background(), corelib.UserKey+userName).Result(); err != nil {
return model.SysUser{}, err
}
if err = corelib.JsonUnmarshal([]byte(userCache), &user); err != nil {
return model.SysUser{}, err
}
return user, nil
}