浏览代码

feat:用户功能缓存模式调整

wangshan 3 年之前
父节点
当前提交
0531bebb88

二进制
api/api.exe


+ 98 - 124
entity/user.go

@@ -2,7 +2,9 @@ package entity
 
 import (
 	MC "app.yhyue.com/moapp/jybase/common"
-	"github.com/zeromicro/go-zero/core/logx"
+	"app.yhyue.com/moapp/jybase/redis"
+	"encoding/json"
+	"fmt"
 	"sync"
 	"time"
 )
@@ -12,6 +14,7 @@ const (
 	BigMemberUserPowerTable = "bigmember_service_user"
 	RedisCode               = "newother"
 	RedisMenuKey            = "jy_workdesktopmenu_%s_%s"
+	UserPowerRedisKey       = "jy_userpowerredis_%s_%s"
 )
 
 var (
@@ -22,153 +25,124 @@ var (
 	UserPowerOutTime = 3 * time.Minute
 )
 
+/*
+*待调整  调整为存redis
+*测试用例放的地方不对 待调整
+ */
 //用户权限 初始化
-func AutoUserPowerInfo(userId string, internalTime int, bigMemberOff bool) map[string]int {
+func AutoUserPowerInfo(userId, appId string, internalTime int, bigMemberOff bool) map[string]int {
 	/*
 	* 商机管理--》新版商机管理vs老版商机管理
 	* 大会员--》bigmember_service
 	* 超级订阅--》新版超级订阅vs老版超级订阅
 	* 免费用户--》新免费用户
 	 */
-	if UserPowerMapMap[userId] == nil {
-		PowerLock.Lock()
-		UserPowerLock[userId] = &sync.Mutex{}
-		UserPowerMapMap[userId] = map[string]int{}
-		PowerLock.Unlock()
+	//redis newother 查询是否存在用户功能信息
+	userPowerRedisKey := fmt.Sprintf(UserPowerRedisKey, appId, userId)
+	bytes, err := redis.GetBytes(RedisCode, userPowerRedisKey)
+	if err == nil && len(*bytes) > 0 {
+		var userPowerData = map[string]int{}
+		if err = json.Unmarshal(*bytes, &userPowerData); err == nil {
+			return userPowerData
+		}
+	}
 
-		UserPowerLock[userId].Lock()
-		defer UserPowerLock[userId].Unlock()
+	PowerLock.Lock()
+	if UserPowerLock[userId] == nil {
+		UserPowerLock[userId] = &sync.Mutex{}
+	}
+	UserPowerMapMap[userId] = map[string]int{}
+	PowerLock.Unlock()
+	UserPowerLock[userId].Lock()
+	defer UserPowerLock[userId].Unlock()
 
-		//查询用户信息
-		data, ok := Mgo.FindById("user", userId, `{"s_phone":1,"s_m_phone":1,i_member_status":1,"s_member_mainid":1,"i_member_sub_status":1,"i_vip_status":1,"o_vipjy":1,"o_jy":1,"l_registedate":1}`)
-		if ok && *data != nil && len(*data) > 0 {
-			phone, _ := MC.If((*data)["s_phone"] != nil, (*data)["s_phone"], (*data)["s_m_phone"]).(string)
-			if phone != "" {
-				//商机管理用户
-				//同一个手机号 多个商机管理角色 其中一个是企业管理员或者部门管理员 查的时候按角色权重排序
-				entNicheInfos := Mysql.SelectBySql(`SELECT i.isNew,r.role_id  FROM (entniche_user u LEFT JOIN entniche_user_role r ON r.user_id = u.id)  LEFT JOIN entniche_info i ON u.ent_id=i.id WHERE u.phone = ? and u.power=1 and i.status=1 ORDER BY r.role_id DESC`, phone)
-				//商机管理用户信息判断
-				if entNicheInfos != nil && len(*entNicheInfos) > 0 {
-					entNicheInfo := (*entNicheInfos)[0]
-					if MC.ObjToString(entNicheInfo["isNew"]) != "" {
-						switch MC.ObjToString(entNicheInfo["isNew"]) {
-						case "1": //新版商机管理
-							UserPowerMapMap[userId]["110"] = 1
-							switch MC.ObjToString(entNicheInfo["role_id"]) {
-							case "1": //部门管理员
-								UserPowerMapMap[userId]["111"] = 1
-							case "2": //企业管理员
-								UserPowerMapMap[userId]["112"] = 1
-							}
-						case "0": //老版商机管理
-							UserPowerMapMap[userId]["100"] = 1
-							switch MC.ObjToString(entNicheInfo["role_id"]) {
-							case "1": //部门管理员
-								UserPowerMapMap[userId]["101"] = 1
-							case "2": //企业管理员
-								UserPowerMapMap[userId]["102"] = 1
-							}
+	//查询用户信息
+	data, ok := Mgo.FindById("user", userId, `{"s_phone":1,"s_m_phone":1,i_member_status":1,"s_member_mainid":1,"i_member_sub_status":1,"i_vip_status":1,"o_vipjy":1,"o_jy":1,"l_registedate":1}`)
+	if ok && *data != nil && len(*data) > 0 {
+		phone, _ := MC.If((*data)["s_phone"] != nil, (*data)["s_phone"], (*data)["s_m_phone"]).(string)
+		if phone != "" {
+			//商机管理用户
+			//同一个手机号 多个商机管理角色 其中一个是企业管理员或者部门管理员 查的时候按角色权重排序
+			entNicheInfos := Mysql.SelectBySql(`SELECT i.isNew,r.role_id  FROM (entniche_user u LEFT JOIN entniche_user_role r ON r.user_id = u.id)  LEFT JOIN entniche_info i ON u.ent_id=i.id WHERE u.phone = ? and u.power=1 and i.status=1 ORDER BY r.role_id DESC`, phone)
+			//商机管理用户信息判断
+			if entNicheInfos != nil && len(*entNicheInfos) > 0 {
+				entNicheInfo := (*entNicheInfos)[0]
+				if MC.ObjToString(entNicheInfo["isNew"]) != "" {
+					switch MC.ObjToString(entNicheInfo["isNew"]) {
+					case "1": //新版商机管理
+						UserPowerMapMap[userId]["110"] = 1
+						switch MC.ObjToString(entNicheInfo["role_id"]) {
+						case "1": //部门管理员
+							UserPowerMapMap[userId]["111"] = 1
+						case "2": //企业管理员
+							UserPowerMapMap[userId]["112"] = 1
+						}
+					case "0": //老版商机管理
+						UserPowerMapMap[userId]["100"] = 1
+						switch MC.ObjToString(entNicheInfo["role_id"]) {
+						case "1": //部门管理员
+							UserPowerMapMap[userId]["101"] = 1
+						case "2": //企业管理员
+							UserPowerMapMap[userId]["102"] = 1
 						}
 					}
 				}
-				//大会员
-				if memberStatus := MC.IntAll((*data)["i_member_status"]); memberStatus > 0 || bigMemberOff {
-					userId := userId
-					if memberStatus > 0 {
-						UserPowerMapMap[userId]["1"] = memberStatus
-						//是否是子账号 而且 子账号被启用
-						if (*data)["s_member_mainid"] != nil && MC.ObjToString((*data)["s_member_mainid"]) != "" && MC.IntAllDef((*data)["i_member_sub_status"], 0) > 0 {
-							userId = MC.ObjToString((*data)["s_member_mainid"])
-						}
+			}
+			//大会员
+			if memberStatus := MC.IntAll((*data)["i_member_status"]); memberStatus > 0 || bigMemberOff {
+				userId := userId
+				if memberStatus > 0 {
+					UserPowerMapMap[userId]["1"] = memberStatus
+					//是否是子账号 而且 子账号被启用
+					if (*data)["s_member_mainid"] != nil && MC.ObjToString((*data)["s_member_mainid"]) != "" && MC.IntAllDef((*data)["i_member_sub_status"], 0) > 0 {
+						userId = MC.ObjToString((*data)["s_member_mainid"])
 					}
-					//大会员用户购买的服务
-					serviceList := Mysql.Find(BigMemberUserPowerTable, map[string]interface{}{"s_userid": userId, "i_status": 0}, "DISTINCT(s_serviceid),i_frequency", "", -1, -1)
-					if serviceList != nil && len(*serviceList) != 0 {
-						for _, sv := range *serviceList {
-							UserPowerMapMap[userId][MC.ObjToString(sv["s_serviceid"])] = MC.IntAll(sv["i_frequency"])
-						}
+				}
+				//大会员用户购买的服务
+				serviceList := Mysql.Find(BigMemberUserPowerTable, map[string]interface{}{"s_userid": userId, "i_status": 0}, "DISTINCT(s_serviceid),i_frequency", "", -1, -1)
+				if serviceList != nil && len(*serviceList) != 0 {
+					for _, sv := range *serviceList {
+						UserPowerMapMap[userId][MC.ObjToString(sv["s_serviceid"])] = MC.IntAll(sv["i_frequency"])
 					}
 				}
-				//VIP用户
-				if vipStatus := MC.IntAll((*data)["i_vip_status"]); vipStatus > 0 {
-					UserPowerMapMap[userId]["200"] = vipStatus
-					if vipSet := MC.ObjToMap((*data)["o_vipjy"]); vipSet != nil {
-						if buySet := MC.ObjToMap((*vipSet)["o_buyset"]); buySet != nil {
-							//vip 升级用户
-							if MC.IntAll((*buySet)["upgrade"]) > 0 {
-								UserPowerMapMap[userId]["201"] = vipStatus
-							}
+			}
+			//VIP用户
+			if vipStatus := MC.IntAll((*data)["i_vip_status"]); vipStatus > 0 {
+				UserPowerMapMap[userId]["200"] = vipStatus
+				if vipSet := MC.ObjToMap((*data)["o_vipjy"]); vipSet != nil {
+					if buySet := MC.ObjToMap((*vipSet)["o_buyset"]); buySet != nil {
+						//vip 升级用户
+						if MC.IntAll((*buySet)["upgrade"]) > 0 {
+							UserPowerMapMap[userId]["201"] = vipStatus
 						}
 					}
 				}
-				//免费用户
-				freeSet := MC.ObjToMap((*data)["o_jy"])
-				if MC.IntAll((*freeSet)["i_newfree"]) > 0 || IsNewFreeTimeCell < MC.IntAll((*data)["l_registedate"]) {
-					//新免费用户
-					UserPowerMapMap[userId]["300"] = 1
-				}
-				//广东移动DICT
-				if Mysql.CountBySql(`select count(*) from privatedata where phone = ?`, phone) > 0 {
-					UserPowerMapMap[userId]["400"] = 1
-				}
 			}
-		}
-		go func(userId string) {
-			//默认存2分钟
-			time.AfterFunc(time.Duration(internalTime)*time.Second, func() {
-				UserPowerPools <- userId
-			})
-		}(userId)
-	}
-	return UserPowerMapMap[userId]
-}
-
-//定时清用户权限缓存
-func ClearUserPower() {
-	for {
-		select {
-		case userId := <-UserPowerPools:
-			logx.Info("-获取 userId:-", userId)
-			if userId != "" {
-				go ClearFunc(userId)
+			//免费用户
+			freeSet := MC.ObjToMap((*data)["o_jy"])
+			if MC.IntAll((*freeSet)["i_newfree"]) > 0 || IsNewFreeTimeCell < MC.IntAll((*data)["l_registedate"]) {
+				//新免费用户
+				UserPowerMapMap[userId]["300"] = 1
+			}
+			//广东移动DICT
+			if Mysql.CountBySql(`select count(*) from privatedata where phone = ?`, phone) > 0 {
+				UserPowerMapMap[userId]["400"] = 1
 			}
-		case <-time.After(UserPowerOutTime):
-			logx.Info("-超时-", UserPowerOutTime)
-			//超时时间累加
-			UserPowerOutTime += UserPowerOutTime
 		}
-	}
-}
-
-//clear One
-func ClearFunc(userId string) {
-	PowerLock.Lock()
-	userPower := UserPowerMapMap[userId]
-	PowerLock.Unlock()
-	if userPower != nil {
-		logx.Info("--清除 userId:--", userId)
-		func() {
-			UserPowerLock[userId].Lock()
-			defer UserPowerLock[userId].Lock()
+		if UserPowerMapMap[userId] != nil {
 			PowerLock.Lock()
-			delete(UserPowerMapMap, userId)
-			PowerLock.Unlock()
-		}()
-	}
-}
-
-//clear all
-func ClearFuncAll() {
-	PowerLock.Lock()
-	if UserPowerMapMap != nil {
-		for uk, _ := range UserPowerMapMap {
-			UserPowerLock[uk].Lock()
-			defer UserPowerLock[uk].Unlock()
-			PowerLock.Lock()
-			delete(UserPowerMapMap, uk)
+			bytes, err := json.Marshal(UserPowerMapMap[userId])
+			if err == nil && len(bytes) > 0 {
+				redis.PutBytes(RedisCode, userPowerRedisKey, &bytes, internalTime)
+			}
 			PowerLock.Unlock()
 		}
 	}
-	PowerLock.Unlock()
+	return UserPowerMapMap[userId]
+}
 
+//clear One
+func ClearUserPowerFunc(userId, appId string) {
+	userPowerRedisKey := fmt.Sprintf(UserPowerRedisKey, appId, userId)
+	redis.Del(RedisCode, userPowerRedisKey)
 }

+ 2 - 6
entity/workDesktop.go

@@ -15,6 +15,7 @@ import (
 type WorkDesktopMenu struct {
 	MenuTree     []*JYMenu
 	UserId       string
+	AppId        string
 	TimeOut      int
 	BigMemberOff bool
 }
@@ -190,12 +191,7 @@ func (m *WorkDesktopMenu) VerifyPermissions(powerIds string) (b bool) {
 		return true
 	}
 	if len(strings.Split(powerIds, ",")) > 0 {
-		PowerLock.Lock()
-		userPower := UserPowerMapMap[m.UserId]
-		PowerLock.Unlock()
-		if userPower == nil {
-			userPower = AutoUserPowerInfo(m.UserId, m.TimeOut, m.BigMemberOff)
-		}
+		userPower := AutoUserPowerInfo(m.UserId, m.AppId, m.TimeOut, m.BigMemberOff)
 		func(powerIds string) {
 			UserPowerLock[m.UserId].Lock()
 			defer UserPowerLock[m.UserId].Unlock()

+ 1 - 1
rpc/etc/usercenter.yaml

@@ -42,7 +42,7 @@ Timeout: 5000
 RedisAddrees:
   - newother=192.168.3.206:1712
 RedisOutTime: 300
-InternalTime: 20
+InternalTime: 7200
 Mongo:
   Main:
     dbName: qfw

+ 1 - 3
rpc/internal/logic/workdesktopclearuserinfologic.go

@@ -34,10 +34,8 @@ func (l *WorkDesktopClearUserInfoLogic) WorkDesktopClearUserInfo(in *pb.WorkDesk
 		//in.UserIds 为空;清全部
 		if in.UserIds != "" {
 			for _, uv := range strings.Split(in.UserIds, ",") {
-				go entity.ClearFunc(uv)
+				go entity.ClearUserPowerFunc(uv, in.AppId)
 			}
-		} else {
-			go entity.ClearFuncAll()
 		}
 	} else {
 		r.ErrorCode = -1

+ 0 - 14
rpc/internal/logic/workdesktopmenuinfologic.go

@@ -2,8 +2,6 @@ package logic
 
 import (
 	"context"
-	"log"
-	"userCenter/entity"
 	"userCenter/rpc/internal/config"
 	"userCenter/service"
 
@@ -27,8 +25,6 @@ func NewWorkDesktopMenuInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext
 	}
 }
 
-var clearUserPowerSwitch = true
-
 // 获取菜单树
 func (l *WorkDesktopMenuInfoLogic) WorkDesktopMenuInfo(in *pb.WorkDesktopMenuInfoReq) (*pb.WorkDesktopMenuInfoResp, error) {
 	if in.UserId == "" {
@@ -38,16 +34,6 @@ func (l *WorkDesktopMenuInfoLogic) WorkDesktopMenuInfo(in *pb.WorkDesktopMenuInf
 			Data:      nil,
 		}, nil
 	}
-	//用户权限信息
-	//go entity.AutoUserPowerInfo(in.UserId, config.ConfigJson.InternalTime, config.ConfigJson.BigMemberOff)
-	//定时启动清除用户权限内存信息
-	log.Println("clearUserPowerSwitch:", clearUserPowerSwitch)
-	if clearUserPowerSwitch {
-		clearUserPowerSwitch = false
-		go func() {
-			entity.ClearUserPower()
-		}()
-	}
 	var (
 		errorCode int64 = 0
 		errorMsg        = ""

二进制
rpc/rpc.exe


+ 2 - 0
service/workDesktop.go

@@ -59,6 +59,7 @@ func RenewWorkDesktopMenuModeOrCommonly(in *WorkDesktopComprehensiveReq, size in
 					var m = &entity.WorkDesktopMenu{
 						MenuTree:     nil,
 						UserId:       in.UserId,
+						AppId:        in.AppId,
 						TimeOut:      redisOutTime,
 						BigMemberOff: bigMemberOff,
 					}
@@ -160,6 +161,7 @@ func GetWordDesktopMenuTree(in *WorkDesktopMenuInfoReq, redisOutTime, internalTi
 	wdm := &entity.WorkDesktopMenu{
 		MenuTree:     []*entity.JYMenu{},
 		UserId:       in.UserId,
+		AppId:        in.AppId,
 		TimeOut:      internalTime,
 		BigMemberOff: bigMemberOff,
 	}