瀏覽代碼

查询缓存添加

WH01243 2 年之前
父節點
當前提交
3bef691e7b

+ 1 - 0
entity/message.go

@@ -14,6 +14,7 @@ var Engine *xorm.Engine
 var EtcdCli *clientv3.Client
 var Mysql *mysql.Mysql
 var Mysql11 *sql.DB
+var SurvivalTime int
 
 type Message struct {
 	Id            string    `xorm:"id" form:"id" json:"id"`

+ 49 - 0
entity/util.go

@@ -0,0 +1,49 @@
+package entity
+
+import (
+	"app.yhyue.com/moapp/MessageCenter/rpc/message"
+	"app.yhyue.com/moapp/jybase/redis"
+	"encoding/json"
+	"fmt"
+)
+
+const (
+	Date_Full_Layout          = "2006-01-02 15:04:05"
+	SOCIALIZE_CHAT_SESSION    = "socialize_chat_session"
+	SOCIALIZE_MESSAGE         = "socialize_message"
+	SOCIALIZE_MESSAGE_MAILBOX = "socialize_message_mailbox"
+	SOCIALIZE_TENANT_ROBOT    = "socialize_tenant_robot"
+	BASE_USER                 = "base_user"
+)
+const (
+	SUCCESS_CODE = int64(0)
+	ERROR_CODE   = int64(1)
+)
+const redisModule = "msgCount"
+
+type SubPush struct {
+	Data  []*message.Messages `json:"data"`
+	Count int64               `json:"count"`
+}
+
+// 获取redis key
+func todayKey(userId string) string {
+	return fmt.Sprintf("%s_%s", "messageCount", userId)
+}
+func GetData(userId string) (*SubPush, error) {
+	pc_a, err := redis.GetNewBytes(redisModule, todayKey(userId))
+	if err != nil {
+		return nil, err
+	}
+	if pc_a == nil {
+		return nil, nil
+	}
+	var p *SubPush
+	if err := json.Unmarshal(*pc_a, &p); err != nil {
+		return nil, err
+	}
+	return p, nil
+}
+func SetData(userId string, data map[string]interface{}, survivalTime int) {
+	redis.Put(redisModule, todayKey(userId), data, survivalTime)
+}

+ 2 - 1
rpc/etc/message.yaml

@@ -22,4 +22,5 @@ FileSystemConf:
   Etcd:
     Hosts:
       - 127.0.0.1:2379
-    Key: message.rpc
+    Key: message.rpc
+SurvivalTime:  86400

+ 4 - 3
rpc/internal/config/config.go

@@ -6,9 +6,10 @@ import (
 
 type Config struct {
 	zrpc.RpcServerConf
-	DataSource *mysqlConfig // 手动代码
-	Mysql      string
-	Redis      *RedisConfig
+	DataSource   *mysqlConfig // 手动代码
+	Mysql        string
+	Redis        *RedisConfig
+	SurvivalTime int
 }
 
 type RedisConfig struct {

+ 1 - 1
rpc/internal/logic/deletemultiplemessagelogic.go

@@ -34,7 +34,7 @@ func (l *DeleteMultipleMessageLogic) DeleteMultipleMessage(in *message.DeleteMul
 	for _, v := range tmpList {
 		idSlice = append(idSlice, v)
 	}
-	code, msg := m.DeleteMessage(idSlice,in.Appid)
+	code, msg := m.DeleteMessage(idSlice, in.Appid)
 	return &message.Response{
 		Code:    code,
 		Message: msg,

+ 1 - 1
rpc/internal/logic/findusermsglogic.go

@@ -26,6 +26,6 @@ func NewFindUserMsgLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FindU
 // 查询指定用户的历史消息记录
 func (l *FindUserMsgLogic) FindUserMsg(in *message.FindUserMsgReq) (*message.FindUserMsgRes, error) {
 	// todo: add your logic here and delete this line
-	data := service.FindUserMsg(*in)
+	data := service.FindUserMsg(*in, false)
 	return &data, nil
 }

+ 14 - 4
service/messageService.go

@@ -25,7 +25,7 @@ func (service *MessageService) ChangeReadStatus(data *message.ChangeReadStatusRe
 	if !b {
 		return 0, "修改消息阅读状态失败"
 	}
-	MsgCountMinusOne(qutil.ObjToString((*msg)["receive_userid"]), strconv.Itoa(int((*msg)["msg_type"].(int64))))
+	MsgCountMinusOne(qutil.ObjToString((*msg)["receive_userid"]), strconv.Itoa(int((*msg)["msg_type"].(int64))), data.Appid)
 	return 1, "修改消息阅读状态成功"
 }
 
@@ -33,6 +33,10 @@ func (service *MessageService) ChangeReadStatus(data *message.ChangeReadStatusRe
 func (service *MessageService) DeleteMessage(id []string, appId string) (int64, string) {
 	orm := entity.Engine.NewSession()
 	defer orm.Close()
+	msg := entity.Mysql.FindOne("message", map[string]interface{}{"id": id, "appid": appId}, "", "")
+	if msg == nil {
+		return 0, "该消息不存在"
+	}
 	m := entity.Message{}
 	m.Isdel = -1
 	count, err := orm.Where("appid=?", appId).In("id", id).Cols("isdel").Update(&m)
@@ -45,6 +49,14 @@ func (service *MessageService) DeleteMessage(id []string, appId string) (int64,
 	if err2 != nil {
 		return 0, "删除消息失败"
 	}
+	FindUserMsg(message.FindUserMsgReq{
+		UserId:   qutil.ObjToString((*msg)["receive_userid"]),
+		Appid:    appId,
+		OffSet:   0,
+		PageSize: 5,
+		MsgType:  -1,
+		Read:     0,
+	}, true)
 	return 1, "删除消息成功"
 }
 
@@ -76,7 +88,6 @@ func (service *MessageService) LastMessage(userId string, appId string, msgType
 		"msg_type":       msgType,
 	}
 	lastMsg := entity.Mysql.FindOne("message", query, "", "createtime desc")
-
 	if lastMsg != nil && len(*lastMsg) > 0 {
 		_id := util.Int64All((*lastMsg)["id"])
 		id := strconv.FormatInt(_id, 10)
@@ -127,7 +138,6 @@ func (service *MessageService) ClassCountAndMessage(userId string, appId string)
 			typeCount = append(typeCount, &message.ResCount{MsgType: v["msg_type"].(int64), Count: v["count"].(int64)})
 		}
 	}
-
 	return typeCount, nil
 }
 
@@ -157,6 +167,6 @@ func (service *MessageService) UpdateMessageReadStatus(msgType int, receiveUseri
 	if !b {
 		return 0, errors.New("修改消息已读出错")
 	}
-	MsgCountZero(receiveUserid, strconv.Itoa(msgType))
+	MsgCountZero(receiveUserid, strconv.Itoa(msgType), appId)
 	return 1, nil
 }

+ 58 - 22
service/sendMsg.go

@@ -1,6 +1,9 @@
 package service
 
 import (
+	"app.yhyue.com/moapp/MessageCenter/entity"
+	"app.yhyue.com/moapp/MessageCenter/rpc/message"
+	"app.yhyue.com/moapp/MessageCenter/util"
 	"app.yhyue.com/moapp/jybase/redis"
 	"database/sql"
 	"fmt"
@@ -9,10 +12,6 @@ import (
 	"strconv"
 	"strings"
 	"time"
-
-	"app.yhyue.com/moapp/MessageCenter/entity"
-	"app.yhyue.com/moapp/MessageCenter/rpc/message"
-	"app.yhyue.com/moapp/MessageCenter/util"
 )
 
 // 类型的顺序
@@ -20,13 +19,7 @@ const order = "1,4"
 const MsgCountKey = "count_%s_%s" //redis 消息未读数量 Count.用户id.消息类型=数量
 const redisModule = "msgCount"
 
-/*var (
-	UserLockMap = map[string]*sync.Mutex{}
-	//MainLock    = sync.Mutex{}
-)*/
-
 func SendMsg(this message.SendMsgRequest) (int64, string) {
-
 	r, err := entity.Mysql11.Query("select count(*) as c from conversation where receive_id = ? and send_id = ? ", this.ReceiveUserId, this.SendUserId)
 	c := 0
 	for r.Next() {
@@ -65,15 +58,13 @@ func SendMsg(this message.SendMsgRequest) (int64, string) {
 	}
 	_, err = entity.Mysql11.Exec(sql3)
 	if err == nil {
-		MsgCountAdd(this.ReceiveUserId, strconv.Itoa(int(this.MsgType)))
+		MsgCountAdd(this.ReceiveUserId, strconv.Itoa(int(this.MsgType)), this.Appid)
 		return 1, "消息发送成功"
 	}
 	return 0, "消息发送失败"
 }
 
-func FindUserMsg(this message.FindUserMsgReq) message.FindUserMsgRes {
-	//orm := entity.Engine
-	//var messages []*entity.Message
+func FindUserMsg(this message.FindUserMsgReq, isClean bool) message.FindUserMsgRes {
 	var err error
 	var count int64
 	cquery := map[string]interface{}{
@@ -87,9 +78,22 @@ func FindUserMsg(this message.FindUserMsgReq) message.FindUserMsgRes {
 	if this.Read != -1 {
 		cquery["isRead"] = this.Read
 	}
-	count = entity.Mysql.Count("message", cquery)
-	//count, err = orm.Table("message").Where("((receive_userid = ? and send_userid = ?) or (receive_userid = ? and send_userid = ?)) and isdel = ? and appid = ?"+q, this.UserId, this.ReceiveUserId, this.ReceiveUserId, this.UserId, 1, this.Appid).Count()
 	data := message.FindUserMsgRes{}
+	if this.PageSize == 5 {
+		//从缓存里边取数据
+		pc_a, err := entity.GetData(this.UserId)
+		if err == nil && pc_a != nil {
+			// 缓存有值
+			if !isClean {
+				data.Code = 1
+				data.Message = "查询成功"
+				data.Data = pc_a.Data
+				data.Count = pc_a.Count
+				return data
+			}
+		}
+	}
+	count = entity.Mysql.Count("message", cquery)
 	if count > 0 {
 		res := entity.Mysql.Find("message", cquery, "", "createtime desc", (int(this.OffSet)-1)*int(this.PageSize), int(this.PageSize))
 		//log.Println("数据:", res)
@@ -117,6 +121,13 @@ func FindUserMsg(this message.FindUserMsgReq) message.FindUserMsgRes {
 		}
 	}
 	data.Count = count
+	if this.PageSize == 5 {
+		redisData := map[string]interface{}{
+			"count": count,
+			"data":  data.Data,
+		}
+		entity.SetData(this.UserId, redisData, entity.SurvivalTime)
+	}
 	if err != nil {
 		data.Code = 0
 		data.Message = "查询失败"
@@ -141,15 +152,31 @@ func ClassCountUnread(msgType int, userId string, appId string) (int64, string,
 }
 
 // MsgCountAdd 消息未读数量加1
-func MsgCountAdd(userId, msgType string) bool {
+func MsgCountAdd(userId, msgType, appId string) bool {
 	keyString := fmt.Sprintf(MsgCountKey, userId, msgType)
 	in := redis.Incr(redisModule, keyString)
+	FindUserMsg(message.FindUserMsgReq{
+		UserId:   userId,
+		Appid:    appId,
+		OffSet:   0,
+		PageSize: 5,
+		MsgType:  -1,
+		Read:     0,
+	}, true)
 	return in > 0
 }
 
 // MsgCountMinusOne 根据消息类型未读消息数量减1
-func MsgCountMinusOne(userId, msgType string) bool {
+func MsgCountMinusOne(userId, msgType, appId string) bool {
 	keyString := fmt.Sprintf(MsgCountKey, userId, msgType)
+	FindUserMsg(message.FindUserMsgReq{
+		UserId:   userId,
+		Appid:    appId,
+		OffSet:   0,
+		PageSize: 5,
+		MsgType:  -1,
+		Read:     0,
+	}, true)
 	if redis.GetInt(redisModule, keyString) <= 0 {
 		return redis.Put(redisModule, keyString, 0, -1)
 	}
@@ -158,9 +185,18 @@ func MsgCountMinusOne(userId, msgType string) bool {
 }
 
 // MsgCountZero 把该消息类型未读数量置0
-func MsgCountZero(userId, msgType string) bool {
+func MsgCountZero(userId, msgType, appId string) bool {
 	keyString := fmt.Sprintf(MsgCountKey, userId, msgType)
-	return redis.Put(redisModule, keyString, 0, -1)
+	fool := redis.Put(redisModule, keyString, 0, -1)
+	FindUserMsg(message.FindUserMsgReq{
+		UserId:   userId,
+		Appid:    appId,
+		OffSet:   0,
+		PageSize: 5,
+		MsgType:  -1,
+		Read:     0,
+	}, true)
+	return fool
 }
 
 func MultSave(this message.MultipleSaveMsgReq) (int64, string) {
@@ -197,13 +233,13 @@ func MultSave(this message.MultipleSaveMsgReq) (int64, string) {
 					errCount++
 					continue
 				}
-				ok1 := MsgCountAdd(v, strconv.Itoa(int(this.MsgType)))
+				ok1 := MsgCountAdd(v, strconv.Itoa(int(this.MsgType)), this.Appid)
 				log.Println("存redis:", ok1)
 			} else {
 				in := entity.Mysql.InsertBySql(sql3)
 				logx.Info("插入消息返回 in1 id:", in)
 				if in > -1 {
-					ok := MsgCountAdd(v, strconv.Itoa(int(this.MsgType)))
+					ok := MsgCountAdd(v, strconv.Itoa(int(this.MsgType)), this.Appid)
 					log.Println("存redis:", ok)
 				} else {
 					errCount++