websocket_msg.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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. "sync"
  9. "time"
  10. "runtime"
  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. err := utils.Rc.BrpopWithTimeout(cacheKey, 30*time.Second, func(b []byte) {
  58. utils.FileLog.Info("收到巡检信息开始处理, adminId:%d", adminId)
  59. messageList, err := data.GetHistoryInspectionMessages(adminId)
  60. if err != nil {
  61. utils.FileLog.Error("获取巡检信息历史失败,err:%s, adminId:%d", err.Error(), adminId)
  62. return
  63. }
  64. if len(messageList) == 0 {
  65. utils.FileLog.Info("巡检信息历史为空, adminId:%d", adminId)
  66. return
  67. }
  68. readList := make([]int64, 0)
  69. // 检查连接状态
  70. conn := global.MonitorMessageConn[adminId]
  71. if conn == nil {
  72. utils.FileLog.Error("发送消息时发现连接已断开, adminId:%d", adminId)
  73. cancel()
  74. return
  75. }
  76. // 只处理第一条消息的发送,其他消息只标记为已读
  77. for i, msg := range messageList {
  78. if i == 0 {
  79. respData, err := data.SendInspectionMessages(adminId, msg)
  80. if err != nil {
  81. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", err.Error(), adminId)
  82. continue
  83. }
  84. resp := models.WebsocketMessageResponse{
  85. MessageType: 1,
  86. Data: respData,
  87. }
  88. err = WriteWebSocketMessageAsync(ctx, adminId, resp)
  89. if err != nil {
  90. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", err.Error(), adminId)
  91. continue
  92. }
  93. utils.FileLog.Info("巡检信息发送成功,adminId:%d, messageId:%d", adminId, msg.MessageId)
  94. }
  95. readList = append(readList, msg.MessageId)
  96. }
  97. if len(readList) > 0 {
  98. _, err = data.ReadEdbInspectionMessageList(readList, adminId)
  99. if err != nil {
  100. utils.FileLog.Error("巡检信息已读失败,err:%s, adminId:%d", err.Error(), adminId)
  101. }
  102. }
  103. })
  104. if err != nil && err.Error() != "redis: nil" {
  105. utils.FileLog.Error("Redis operation failed: %v", err)
  106. continue
  107. }else {
  108. utils.FileLog.Info("巡检信息处理完成, adminId:%d", adminId)
  109. }
  110. }
  111. }
  112. }
  113. func WriteWebSocketMessageAsync(ctx context.Context, adminId int, resp interface{}) error {
  114. errChan := make(chan error, 1)
  115. var wsWriteMutex sync.Mutex
  116. go func() {
  117. wsWriteMutex.Lock()
  118. defer wsWriteMutex.Unlock()
  119. conn := global.MonitorMessageConn[adminId]
  120. if conn == nil {
  121. errChan <- fmt.Errorf("connection closed for adminId: %d", adminId)
  122. return
  123. }
  124. // 设置写超时
  125. //conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
  126. errChan <- conn.WriteJSON(resp)
  127. }()
  128. select {
  129. case err := <-errChan:
  130. utils.FileLog.Error("WriteWebSocketMessageAsync errChan: %v", err)
  131. return err
  132. case <-ctx.Done():
  133. utils.FileLog.Error("WriteWebSocketMessageAsync ctx.Done(): %v", ctx.Err())
  134. return ctx.Err()
  135. }
  136. }