websocket_msg.go 3.9 KB

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