sendMsg.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. package service
  2. import (
  3. "app.yhyue.com/moapp/MessageCenter/entity"
  4. "app.yhyue.com/moapp/MessageCenter/rpc/message"
  5. "app.yhyue.com/moapp/MessageCenter/util"
  6. "app.yhyue.com/moapp/jybase/redis"
  7. "database/sql"
  8. "fmt"
  9. "github.com/zeromicro/go-zero/core/logx"
  10. "log"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "time"
  15. )
  16. // 类型的顺序
  17. const order = "1,4"
  18. const MsgCountKey = "count_%s_%s" //redis 消息未读数量 Count.用户id.消息类型=数量
  19. const redisModule = "msgCount"
  20. /*var (
  21. UserLockMap = map[string]*sync.Mutex{}
  22. //MainLock = sync.Mutex{}
  23. )*/
  24. func SendMsg(this message.SendMsgRequest) (int64, string) {
  25. r, err := entity.Mysql11.Query("select count(*) as c from conversation where receive_id = ? and send_id = ? ", this.ReceiveUserId, this.SendUserId)
  26. c := 0
  27. for r.Next() {
  28. err := r.Scan(&c)
  29. if err != nil {
  30. panic(err.Error())
  31. }
  32. }
  33. logx.Info("查询数量:", c)
  34. sql3 := `INSERT INTO message(appid,receive_userid,receive_name,send_userid,send_name,title,content,msg_type,link,cite_id,createtime,isRead,isdel)
  35. values ("%s",'%s','%s','%s','%s','%s','%s','%d','%s',0,'%s',0,1);`
  36. sql3 = fmt.Sprintf(sql3, this.Appid, this.ReceiveUserId, this.ReceiveName, this.SendUserId, this.SendName, this.Title, this.Content, this.MsgType, this.Link, time.Now().Format("2006-01-02 15:04:05"))
  37. if c < 1 {
  38. sql1 := `INSERT INTO conversation(appid,` + "`key`" + `,user_id,receive_id,receive_name,send_id,send_name,sort,createtime)
  39. values ('%s','','%s','%s','%s','%s','%s',0,'%s');`
  40. sql1 = fmt.Sprintf(sql1, this.Appid, this.SendUserId, this.ReceiveUserId, this.ReceiveName, this.SendUserId, this.SendName, time.Now().Format("2006-01-02 15:04:05"))
  41. ok := entity.Mysql.ExecTx("发送消息事务", func(tx *sql.Tx) bool {
  42. //插入会话表
  43. _, err := entity.Mysql11.Exec(sql1)
  44. sql2 := `INSERT INTO conversation(appid,` + "`key`" + `,user_id,receive_id,receive_name,send_id,send_name,sort,createtime)
  45. values ('%s','','%s','%s','%s','%s','%s',0,'%s');`
  46. sql2 = fmt.Sprintf(sql2, this.Appid, this.ReceiveUserId, this.SendUserId, this.SendName, this.ReceiveUserId, this.ReceiveName, time.Now().Format("2006-01-02 15:04:05"))
  47. _, err = entity.Mysql11.Exec(sql2)
  48. //插入消息表
  49. _, err = entity.Mysql11.Exec(sql3)
  50. if err != nil {
  51. return false
  52. }
  53. return true
  54. })
  55. if ok {
  56. return 1, "消息发送成功"
  57. }
  58. }
  59. _, err = entity.Mysql11.Exec(sql3)
  60. if err == nil {
  61. MsgCountAdd(this.ReceiveUserId, strconv.Itoa(int(this.MsgType)), this.Appid)
  62. return 1, "消息发送成功"
  63. }
  64. return 0, "消息发送失败"
  65. }
  66. func FindUserMsg(this message.FindUserMsgReq, isClean bool) message.FindUserMsgRes {
  67. var err error
  68. var count int64
  69. cquery := map[string]interface{}{
  70. "receive_userid": this.UserId,
  71. "isdel": 1,
  72. "appid": this.Appid,
  73. }
  74. if this.MsgType != -1 {
  75. cquery["msg_type"] = this.MsgType
  76. }
  77. if this.Read != -1 {
  78. cquery["isRead"] = this.Read
  79. }
  80. count = entity.Mysql.Count("message", cquery)
  81. data := message.FindUserMsgRes{}
  82. if this.PageSize == 5 {
  83. //从缓存里边取数据
  84. pc_a, err := entity.GetData(this.UserId)
  85. if err == nil && pc_a != nil {
  86. // 缓存有值
  87. if !isClean {
  88. data.Code = 1
  89. data.Message = "查询成功"
  90. data.Data = pc_a.Data
  91. data.Count = pc_a.Count
  92. return data
  93. }
  94. }
  95. }
  96. count = entity.Mysql.Count("message", cquery)
  97. if count > 0 {
  98. res := entity.Mysql.Find("message", cquery, "", "createtime desc", (int(this.OffSet)-1)*int(this.PageSize), int(this.PageSize))
  99. //log.Println("数据:", res)
  100. if res != nil && len(*res) > 0 {
  101. for _, v := range *res {
  102. _id := util.Int64All(v["id"])
  103. id := strconv.FormatInt(_id, 10)
  104. data.Data = append(data.Data, &message.Messages{
  105. Id: id,
  106. Appid: util.ObjToString(v["appId"]),
  107. ReceiveUserId: util.ObjToString(v["receive_userid"]),
  108. ReceiveName: util.ObjToString(v["receive_name"]),
  109. SendUserId: util.ObjToString(v["send_userid"]),
  110. SendName: util.ObjToString(v["send_name"]),
  111. Createtime: util.ObjToString(v["createtime"]),
  112. Title: util.ObjToString(v["title"]),
  113. MsgType: int64(util.IntAll(v["msg_type"])),
  114. Link: util.ObjToString(v["link"]),
  115. CiteId: util.Int64All(v["cite_id"]),
  116. Content: util.ObjToString(v["content"]),
  117. IsRead: util.Int64All(v["isRead"]),
  118. MsgLogId: util.Int64All(v["msg_log_id"]),
  119. })
  120. }
  121. }
  122. }
  123. data.Count = count
  124. if this.PageSize == 5 {
  125. redisData := map[string]interface{}{
  126. "count": count,
  127. "data": data.Data,
  128. }
  129. entity.SetData(this.UserId, redisData, entity.SurvivalTime)
  130. }
  131. if err != nil {
  132. data.Code = 0
  133. data.Message = "查询失败"
  134. } else {
  135. data.Code = 1
  136. data.Message = "查询成功"
  137. }
  138. return data
  139. }
  140. // 指定分类未读消息合计
  141. func ClassCountUnread(msgType int, userId string, appId string) (int64, string, int64) {
  142. query := map[string]interface{}{
  143. "msg_type": msgType,
  144. "receive_userid": userId,
  145. "isdel": 1,
  146. "appid": appId,
  147. "isRead": 0,
  148. }
  149. count := entity.Mysql.Count("message", query)
  150. return 1, "查询指定分类未读消息成功", count
  151. }
  152. // MsgCountAdd 消息未读数量加1
  153. func MsgCountAdd(userId, msgType, appId string) bool {
  154. keyString := fmt.Sprintf(MsgCountKey, userId, msgType)
  155. in := redis.Incr(redisModule, keyString)
  156. FindUserMsg(message.FindUserMsgReq{
  157. UserId: userId,
  158. Appid: appId,
  159. OffSet: 1,
  160. PageSize: 5,
  161. MsgType: -1,
  162. Read: 0,
  163. }, true)
  164. return in > 0
  165. }
  166. // MsgCountMinusOne 根据消息类型未读消息数量减1
  167. func MsgCountMinusOne(userId, msgType, appId string) bool {
  168. keyString := fmt.Sprintf(MsgCountKey, userId, msgType)
  169. FindUserMsg(message.FindUserMsgReq{
  170. UserId: userId,
  171. Appid: appId,
  172. OffSet: 1,
  173. PageSize: 5,
  174. MsgType: -1,
  175. Read: 0,
  176. }, true)
  177. if redis.GetInt(redisModule, keyString) <= 0 {
  178. return redis.Put(redisModule, keyString, 0, -1)
  179. }
  180. in := redis.Decrby(redisModule, keyString, 1)
  181. return in > 0
  182. }
  183. // MsgCountZero 把该消息类型未读数量置0
  184. func MsgCountZero(userId, msgType, appId string) bool {
  185. keyString := fmt.Sprintf(MsgCountKey, userId, msgType)
  186. fool := redis.Put(redisModule, keyString, 0, -1)
  187. FindUserMsg(message.FindUserMsgReq{
  188. UserId: userId,
  189. Appid: appId,
  190. OffSet: 1,
  191. PageSize: 5,
  192. MsgType: -1,
  193. Read: 0,
  194. }, true)
  195. return fool
  196. }
  197. func MultSave(this message.MultipleSaveMsgReq) (int64, string) {
  198. userIdArr := strings.Split(this.UserIds, ",")
  199. userNameArr := strings.Split(this.UserNames, ",")
  200. if len(userIdArr) == 0 {
  201. return 0, "无效的用户id"
  202. }
  203. wg := &sync.WaitGroup{}
  204. for i := 0; i < len(userIdArr); i++ {
  205. v := userIdArr[i]
  206. if v == "" {
  207. continue
  208. }
  209. userName := userNameArr[i]
  210. wg.Add(1)
  211. entity.SaveConcurrencyChan <- 1
  212. go func() {
  213. defer func() {
  214. <-entity.SaveConcurrencyChan
  215. wg.Done()
  216. }()
  217. //消息数组
  218. c := entity.Mysql.Count("conversation", map[string]interface{}{"receive_id": v, "send_id": this.SendUserId})
  219. sql3 := `INSERT INTO message(appid,receive_userid,receive_name,send_userid,send_name,title,content,msg_type,link,cite_id,createtime,isRead,isdel,msg_log_id,show_buoy,show_content) values ("%s",'%s','%s','%s','%s','%s','%s',%d,'%s',0,'%s',0,1,%d,%d,'%s');`
  220. sql3 = fmt.Sprintf(sql3, this.Appid, v, userName, this.SendUserId, this.SendName, this.Title, this.Content, this.MsgType, this.Link, time.Now().Format("2006-01-02 15:04:05"), this.MsgLogId, this.ShowBuoy, this.ShowContent)
  221. if c <= 0 {
  222. sql1 := `INSERT INTO conversation(appid,secret_key,user_id,receive_id,receive_name,send_id,send_name,sort,createtime) values ('%s','','%s','%s','%s','%s','%s',0,'%s');`
  223. sql1 = fmt.Sprintf(sql1, this.Appid, this.SendUserId, v, userName, this.SendUserId, this.SendName, time.Now().Format("2006-01-02 15:04:05"))
  224. ok := entity.Mysql.ExecTx("发送消息事务", func(tx *sql.Tx) bool {
  225. //插入会话表
  226. in1 := entity.Mysql.InsertBySqlByTx(tx, sql1)
  227. sql2 := `INSERT INTO conversation(appid,secret_key,user_id,receive_id,receive_name,send_id,send_name,sort,createtime) values ('%s','','%s','%s','%s','%s','%s',0,'%s');`
  228. sql2 = fmt.Sprintf(sql2, this.Appid, v, this.SendUserId, this.SendName, v, userName, time.Now().Format("2006-01-02 15:04:05"))
  229. in2 := entity.Mysql.InsertBySqlByTx(tx, sql2)
  230. //插入消息表
  231. in3 := entity.Mysql.InsertBySqlByTx(tx, sql3)
  232. logx.Info(in1, in2, in3)
  233. return in1 > -1 && in2 > -1 && in3 > -1
  234. })
  235. logx.Info("执行事务是否成功:", ok)
  236. if ok {
  237. ok1 := MsgCountAdd(v, strconv.Itoa(int(this.MsgType)), this.Appid)
  238. log.Println("存redis:", ok1)
  239. }
  240. } else {
  241. in := entity.Mysql.InsertBySql(sql3)
  242. logx.Info("插入消息返回 in1 id:", in)
  243. if in > -1 {
  244. ok := MsgCountAdd(v, strconv.Itoa(int(this.MsgType)), this.Appid)
  245. log.Println("存redis:", ok)
  246. }
  247. }
  248. }()
  249. }
  250. wg.Wait()
  251. return 0, ""
  252. }