sendMsg.go 8.7 KB

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