websocket_msg.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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. 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. for i, msg := range messageList {
  71. if i == 0 {
  72. respData, err := data.SendInspectionMessages(adminId, msg)
  73. if err != nil {
  74. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", err.Error(), adminId)
  75. continue
  76. }
  77. resp := models.WebsocketMessageResponse{
  78. MessageType: 1,
  79. Data: respData,
  80. }
  81. err, isClose := WriteWebSocketMessageAsync(ctx, adminId, resp)
  82. if err != nil {
  83. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", err.Error(), adminId)
  84. continue
  85. }
  86. if isClose {
  87. utils.FileLog.Error("巡检信息发送失败,连接已断开, adminId:%d", adminId)
  88. cancel()
  89. return
  90. }
  91. utils.FileLog.Info("巡检信息发送成功,adminId:%d, messageId:%d", adminId, msg.MessageId)
  92. }
  93. readList = append(readList, msg.MessageId)
  94. }
  95. if len(readList) > 0 {
  96. _, err = data.ReadEdbInspectionMessageList(readList, adminId)
  97. if err != nil {
  98. utils.FileLog.Error("巡检信息已读失败,err:%s, adminId:%d", err.Error(), adminId)
  99. }
  100. }
  101. })
  102. if err != nil && err.Error() != "redis: nil" {
  103. utils.FileLog.Error("Redis operation failed: %v", err)
  104. continue
  105. }else {
  106. utils.FileLog.Info("巡检信息处理完成, adminId:%d", adminId)
  107. }
  108. }
  109. }
  110. }
  111. func WriteWebSocketMessageAsync(ctx context.Context, adminId int, resp interface{}) (error, bool) {
  112. errChan := make(chan error, 1)
  113. var wsWriteMutex sync.Mutex
  114. isClose := false
  115. go func() {
  116. wsWriteMutex.Lock()
  117. defer wsWriteMutex.Unlock()
  118. conn := global.MonitorMessageConn[adminId]
  119. if conn == nil {
  120. isClose = true
  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, isClose
  132. case <-ctx.Done():
  133. utils.FileLog.Error("WriteWebSocketMessageAsync ctx.Done(): %v", ctx.Err())
  134. return ctx.Err(), isClose
  135. }
  136. }