websocket_msg.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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. go DealEdbInspectionMessage(adminId)
  15. }
  16. // 处理巡检消息
  17. func DealEdbInspectionMessage(adminId int) {
  18. utils.FileLog.Info("创建协程, adminId:%d", adminId)
  19. // 创建上下文用于控制 goroutine 生命周期
  20. ctx, cancel := context.WithCancel(context.Background())
  21. defer cancel()
  22. cacheKey := fmt.Sprintf("%s%d", utils.CACHE_EDB_INSPECTION_MESSAGE, adminId)
  23. // 添加错误恢复机制
  24. defer func() {
  25. if r := recover(); r != nil {
  26. utils.FileLog.Error("WebSocket handler recovered from panic: %v", r)
  27. // 清理资源
  28. cancel()
  29. }
  30. }()
  31. go func() {
  32. ticker := time.NewTicker(time.Minute)
  33. defer ticker.Stop()
  34. for {
  35. select {
  36. case <-ticker.C:
  37. utils.FileLog.Info("Current goroutine count: %d", runtime.NumGoroutine())
  38. case <-ctx.Done():
  39. return
  40. }
  41. }
  42. }()
  43. for {
  44. select {
  45. case <-ctx.Done():
  46. utils.FileLog.Info("DealEdbInspectionMessage 巡检消息处理协程结束, adminId:%d", adminId)
  47. return
  48. default:
  49. // 检查连接状态
  50. conn := global.MonitorMessageConn[adminId]
  51. if conn == nil {
  52. utils.FileLog.Error("检查连接状态 发送消息时发现连接已断开, adminId:%d", adminId)
  53. cancel()
  54. return
  55. }
  56. // 使用带超时的 Redis 操作
  57. val := utils.Rc.Get(cacheKey)
  58. if val == "" {
  59. //utils.FileLog.Info("巡检信息历史为空, adminId:%d", adminId)
  60. continue
  61. }
  62. utils.FileLog.Info("收到巡检信息开始处理, adminId:%d", adminId)
  63. messageList, err := data.GetHistoryInspectionMessages(adminId)
  64. if err != nil {
  65. utils.FileLog.Error("获取巡检信息历史失败,err:%s, adminId:%d", err.Error(), adminId)
  66. return
  67. }
  68. if len(messageList) == 0 {
  69. utils.FileLog.Info("巡检信息历史为空, adminId:%d", adminId)
  70. return
  71. }
  72. readList := make([]int64, 0)
  73. // 检查连接状态
  74. // conn := global.MonitorMessageConn[adminId]
  75. // if conn == nil {
  76. // utils.FileLog.Error("发送消息时发现连接已断开, adminId:%d", adminId)
  77. // cancel()
  78. // return
  79. // }
  80. // 只处理第一条消息的发送,其他消息只标记为已读
  81. for i, msg := range messageList {
  82. if i == 0 {
  83. respData, err := data.SendInspectionMessages(adminId, msg)
  84. if err != nil {
  85. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", err.Error(), adminId)
  86. continue
  87. }
  88. resp := models.WebsocketMessageResponse{
  89. MessageType: 1,
  90. Data: respData,
  91. }
  92. err, isClose := WriteWebSocketMessageAsync(ctx, adminId, resp)
  93. if err != nil {
  94. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", err.Error(), adminId)
  95. continue
  96. }
  97. if isClose {
  98. utils.FileLog.Error("巡检信息发送失败,连接已断开, adminId:%d", adminId)
  99. cancel()
  100. return
  101. }
  102. utils.FileLog.Info("巡检信息发送成功,adminId:%d, messageId:%d", adminId, msg.MessageId)
  103. }
  104. readList = append(readList, msg.MessageId)
  105. }
  106. if len(readList) > 0 {
  107. _, err = data.ReadEdbInspectionMessageList(readList, adminId)
  108. if err != nil {
  109. utils.FileLog.Error("巡检信息已读失败,err:%s, adminId:%d", err.Error(), adminId)
  110. }
  111. }
  112. //})
  113. // if err != nil && err.Error() != "redis: nil" {
  114. // utils.FileLog.Error("Redis operation failed: %v", err)
  115. // continue
  116. // }else {
  117. // utils.FileLog.Info("巡检信息处理完成, adminId:%d", adminId)
  118. // }
  119. }
  120. }
  121. }
  122. func WriteWebSocketMessageAsync(ctx context.Context, adminId int, resp interface{}) (error, bool) {
  123. errChan := make(chan error, 1)
  124. var wsWriteMutex sync.Mutex
  125. isClose := false
  126. go func() {
  127. wsWriteMutex.Lock()
  128. defer wsWriteMutex.Unlock()
  129. conn := global.MonitorMessageConn[adminId]
  130. if conn == nil {
  131. isClose = true
  132. errChan <- fmt.Errorf("connection closed for adminId: %d", adminId)
  133. return
  134. }
  135. // 设置写超时
  136. //conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
  137. errChan <- conn.WriteJSON(resp)
  138. }()
  139. select {
  140. case err := <-errChan:
  141. utils.FileLog.Error("WriteWebSocketMessageAsync errChan: %v", err)
  142. return err, isClose
  143. case <-ctx.Done():
  144. utils.FileLog.Error("WriteWebSocketMessageAsync ctx.Done(): %v", ctx.Err())
  145. return ctx.Err(), isClose
  146. }
  147. }