websocket_msg.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. package services
  2. import (
  3. "eta/eta_api/global"
  4. "eta/eta_api/models"
  5. "eta/eta_api/services/data"
  6. "eta/eta_api/utils"
  7. "fmt"
  8. "runtime"
  9. "sync"
  10. "time"
  11. "context"
  12. )
  13. func DealWebSocketMsg(adminId int) {
  14. DealEdbInspectionMessageTest(adminId)
  15. //go DealEdbInspectionMessage(adminId)
  16. }
  17. // 处理巡检消息
  18. func DealEdbInspectionMessage(adminId int) {
  19. utils.FileLog.Info("创建协程, adminId:%d", adminId)
  20. // 创建上下文用于控制 goroutine 生命周期
  21. ctx, cancel := context.WithCancel(context.Background())
  22. defer cancel()
  23. cacheKey := fmt.Sprintf("%s%d", utils.CACHE_EDB_INSPECTION_MESSAGE, adminId)
  24. // 添加错误恢复机制
  25. defer func() {
  26. if r := recover(); r != nil {
  27. utils.FileLog.Error("WebSocket handler recovered from panic: %v", r)
  28. // 清理资源
  29. cancel()
  30. }
  31. }()
  32. go func() {
  33. ticker := time.NewTicker(time.Minute)
  34. defer ticker.Stop()
  35. for {
  36. select {
  37. case <-ticker.C:
  38. utils.FileLog.Info("Current goroutine count: %d", runtime.NumGoroutine())
  39. case <-ctx.Done():
  40. return
  41. }
  42. }
  43. }()
  44. for {
  45. select {
  46. case <-ctx.Done():
  47. utils.FileLog.Info("DealEdbInspectionMessage 巡检消息处理协程结束, adminId:%d", adminId)
  48. return
  49. default:
  50. // 检查连接状态
  51. conn := global.MonitorMessageConn[adminId]
  52. if conn == nil {
  53. utils.FileLog.Error("检查连接状态 发送消息时发现连接已断开, adminId:%d", adminId)
  54. cancel()
  55. return
  56. }
  57. // 使用带超时的 Redis 操作
  58. val := utils.Rc.Get(cacheKey)
  59. if val == "" {
  60. //utils.FileLog.Info("巡检信息历史为空, adminId:%d", adminId)
  61. continue
  62. }
  63. utils.FileLog.Info("收到巡检信息开始处理, adminId:%d", adminId)
  64. messageList, err := data.GetHistoryInspectionMessages(adminId)
  65. if err != nil {
  66. utils.FileLog.Error("获取巡检信息历史失败,err:%s, adminId:%d", err.Error(), adminId)
  67. return
  68. }
  69. if len(messageList) == 0 {
  70. utils.FileLog.Info("巡检信息历史为空, adminId:%d", adminId)
  71. return
  72. }
  73. readList := make([]int64, 0)
  74. // 检查连接状态
  75. // conn := global.MonitorMessageConn[adminId]
  76. // if conn == nil {
  77. // utils.FileLog.Error("发送消息时发现连接已断开, adminId:%d", adminId)
  78. // cancel()
  79. // return
  80. // }
  81. // 只处理第一条消息的发送,其他消息只标记为已读
  82. for i, msg := range messageList {
  83. if i == 0 {
  84. respData, err := data.SendInspectionMessages(adminId, msg)
  85. if err != nil {
  86. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", err.Error(), adminId)
  87. continue
  88. }
  89. resp := models.WebsocketMessageResponse{
  90. MessageType: 1,
  91. Data: respData,
  92. }
  93. err, isClose := WriteWebSocketMessageAsync(ctx, adminId, resp)
  94. if err != nil {
  95. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", err.Error(), adminId)
  96. cancel()
  97. continue
  98. }
  99. if isClose {
  100. utils.FileLog.Error("巡检信息发送失败,连接已断开, adminId:%d", adminId)
  101. cancel()
  102. return
  103. }
  104. utils.FileLog.Info("巡检信息发送成功,adminId:%d, messageId:%d", adminId, msg.MessageId)
  105. }
  106. readList = append(readList, msg.MessageId)
  107. }
  108. if len(readList) > 0 {
  109. _, err = data.ReadEdbInspectionMessageList(readList, adminId)
  110. if err != nil {
  111. utils.FileLog.Error("巡检信息已读失败,err:%s, adminId:%d", err.Error(), adminId)
  112. }
  113. }
  114. //})
  115. // if err != nil && err.Error() != "redis: nil" {
  116. // utils.FileLog.Error("Redis operation failed: %v", err)
  117. // continue
  118. // }else {
  119. // utils.FileLog.Info("巡检信息处理完成, adminId:%d", adminId)
  120. // }
  121. }
  122. }
  123. }
  124. func WriteWebSocketMessageAsync(ctx context.Context, adminId int, resp interface{}) (error, bool) {
  125. errChan := make(chan error, 1)
  126. var wsWriteMutex sync.Mutex
  127. isClose := false
  128. go func() {
  129. wsWriteMutex.Lock()
  130. defer wsWriteMutex.Unlock()
  131. conn := global.MonitorMessageConn[adminId]
  132. if conn == nil {
  133. isClose = true
  134. errChan <- fmt.Errorf("connection closed for adminId: %d", adminId)
  135. return
  136. }
  137. // 设置写超时
  138. //conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
  139. errChan <- conn.WriteJSON(resp)
  140. }()
  141. select {
  142. case err := <-errChan:
  143. utils.FileLog.Error("WriteWebSocketMessageAsync errChan: %v", err)
  144. return err, isClose
  145. case <-ctx.Done():
  146. utils.FileLog.Error("WriteWebSocketMessageAsync ctx.Done(): %v", ctx.Err())
  147. return ctx.Err(), isClose
  148. }
  149. }
  150. func DealEdbInspectionMessageTest(adminId int) {
  151. messageList, err := data.GetHistoryInspectionMessages(adminId)
  152. if err != nil {
  153. utils.FileLog.Error("获取巡检信息历史失败,err:%s, adminId:%d", err.Error(), adminId)
  154. }
  155. success := make(chan int64, 10)
  156. go func() {
  157. defer close(success)
  158. for i, msg := range messageList {
  159. if i == 0 {
  160. // 多条消息仅发送最新一条
  161. respData, err := data.SendInspectionMessages(adminId, msg)
  162. if err != nil {
  163. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", err.Error(), adminId)
  164. } else {
  165. resp := models.WebsocketMessageResponse{
  166. MessageType: 1,
  167. Data: respData,
  168. }
  169. conn := global.MonitorMessageConn[adminId]
  170. if conn == nil {
  171. utils.FileLog.Error("巡检信息发送失败,连接已断开, adminId:%d", adminId)
  172. return
  173. }
  174. err = conn.WriteJSON(resp)
  175. if err != nil {
  176. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", err.Error(), adminId)
  177. } else {
  178. utils.FileLog.Info("巡检信息发送成功,adminId:%d, messageId:%d", adminId, msg.MessageId)
  179. success <- msg.MessageId
  180. }
  181. }
  182. } else {
  183. success <- msg.MessageId
  184. }
  185. }
  186. }()
  187. go func() {
  188. readList := make([]int64, 0)
  189. for {
  190. msgId, ok := <-success
  191. if !ok {
  192. break
  193. }
  194. readList = append(readList, msgId)
  195. }
  196. _, err = data.ReadEdbInspectionMessageList(readList, adminId)
  197. if err != nil {
  198. utils.FileLog.Error("巡检信息已读失败,err:%s, adminId:%d", err.Error(), adminId)
  199. }
  200. }()
  201. }