websocket_msg.go 3.8 KB

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