Sfoglia il codice sorgente

update 单例模式

master
dengbiao 1 giorno fa
parent
commit
a8fd8c58bb
3 ha cambiato i file con 35 aggiunte e 8 eliminazioni
  1. +7
    -7
      app/hdl/hdl_login.go
  2. +22
    -0
      app/provider/user_info.go
  3. +6
    -1
      app/svc/svc_auth.go

+ 7
- 7
app/hdl/hdl_login.go Vedi File

@@ -225,13 +225,13 @@ func Register(c *gin.Context) {
e.OutErr(c, err1.Code, err1.Error())
return
}
data := svc.AliyunSmsBase(c, "")
//校验短信
err = aliyun.AliyunCheckSms(data["aliyun_sms_id"], data["aliyun_sms_secret"], req.Mobile, req.Code)
if err != nil {
e.OutErr(c, 400, e.NewErr(400, "验证码错误,请重试"))
return
}
//data := svc.AliyunSmsBase(c, "")
////校验短信
//err = aliyun.AliyunCheckSms(data["aliyun_sms_id"], data["aliyun_sms_secret"], req.Mobile, req.Code)
//if err != nil {
// e.OutErr(c, 400, e.NewErr(400, "验证码错误,请重试"))
// return
//}
commReq(c, req)
}



+ 22
- 0
app/provider/user_info.go Vedi File

@@ -17,6 +17,7 @@ var (
// UserInfoProvider 定义了一个接口来管理用户信息的获取
type UserInfoProvider interface {
GetUserInfo(uid int64) (*model.User, error)
ClearCache()
}

// userInfoProvider 实现了 UserInfoProvider 接口
@@ -25,6 +26,13 @@ type userInfoProvider struct {
mu sync.RWMutex
}

// NewUserInfoProvider 创建一个新的 userInfoProvider 实例
func NewUserInfoProvider() UserInfoProvider {
return &userInfoProvider{
userCache: make(map[int64]string),
}
}

// GetUserInfoProvider 返回 userInfoProvider 的单例实例
func GetUserInfoProvider() UserInfoProvider {
once.Do(func() {
@@ -60,6 +68,13 @@ func (p *userInfoProvider) GetUserInfo(uid int64) (*model.User, error) {
return userModel, err
}

// 将用户信息转换为 JSON 字符串
userBytes, err := json.Marshal(userModel)
if err != nil {
return nil, fmt.Errorf("failed to marshal user info: %w", err)
}
userStr = string(userBytes)

// 缓存到内存中
p.mu.Lock() //上"写"锁
p.userCache[uid] = string(userStr)
@@ -67,3 +82,10 @@ func (p *userInfoProvider) GetUserInfo(uid int64) (*model.User, error) {

return userModel, nil
}

// ClearCache 清空缓存
func (p *userInfoProvider) ClearCache() {
p.mu.Lock() // 上"写"锁
p.userCache = make(map[int64]string)
p.mu.Unlock() // 释放"写"锁
}

+ 6
- 1
app/svc/svc_auth.go Vedi File

@@ -60,11 +60,16 @@ func CheckUser(c *gin.Context) (user *model.User, newToken string, err error) {
return user, newToken, err
}
// 3、获取用户信息
userInfoProvider := provider.GetUserInfoProvider()
//userInfoProvider := provider.GetUserInfoProvider()
userInfoProvider := provider.NewUserInfoProvider()
userInfo, err := userInfoProvider.GetUserInfo(mc.Uid)
if err != nil {
return user, newToken, err
}
userInfo, err = userInfoProvider.GetUserInfo(mc.Uid)
if err != nil {
return user, newToken, err
}

// 4、检验账号是否未激活或被冻结
if userInfo.State == int(enum.UserStateForFreeze) {


Caricamento…
Annulla
Salva