websocket_msg.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. package services
  2. import (
  3. "eta/eta_api/models"
  4. "eta/eta_api/services/data"
  5. "eta/eta_api/utils"
  6. "fmt"
  7. "sync"
  8. "time"
  9. "context"
  10. "github.com/gorilla/websocket"
  11. )
  12. func DealWebSocketMsg(conn *websocket.Conn, adminId int) {
  13. go DealEdbInspectionMessage(conn, adminId)
  14. }
  15. // 处理巡检消息
  16. func DealEdbInspectionMessage(conn *websocket.Conn, adminId int) {
  17. // 创建上下文用于控制 goroutine 生命周期
  18. ctx, cancel := context.WithCancel(context.Background())
  19. defer cancel()
  20. // 创建互斥锁保护 WebSocket 写操作
  21. var wsWriteMutex sync.Mutex
  22. // // 监控 goroutine 数量
  23. // go func() {
  24. // ticker := time.NewTicker(time.Minute)
  25. // defer ticker.Stop()
  26. // for {
  27. // select {
  28. // case <-ticker.C:
  29. // utils.FileLog.Info("Current goroutine count: %d", runtime.NumGoroutine())
  30. // case <-ctx.Done():
  31. // return
  32. // }
  33. // }
  34. // }()
  35. cacheKey := fmt.Sprintf("%s%d", utils.CACHE_EDB_INSPECTION_MESSAGE, adminId)
  36. // 设置连接关闭处理器
  37. conn.SetCloseHandler(func(code int, text string) error {
  38. utils.FileLog.Info("长连接关闭, adminId:%d", adminId)
  39. cancel()
  40. return nil
  41. })
  42. // 添加错误恢复机制
  43. defer func() {
  44. if r := recover(); r != nil {
  45. utils.FileLog.Error("WebSocket handler recovered from panic: %v", r)
  46. // 清理资源
  47. cancel()
  48. }
  49. }()
  50. for {
  51. select {
  52. case <-ctx.Done():
  53. return
  54. default:
  55. // 使用带超时的 Redis 操作
  56. err := utils.Rc.BrpopWithTimeout(cacheKey, 30*time.Second, func(b []byte) {
  57. utils.FileLog.Info("收到巡检信息开始处理, adminId:%d", adminId)
  58. messageList, err := data.GetHistoryInspectionMessages(adminId)
  59. if err != nil {
  60. utils.FileLog.Error("获取巡检信息历史失败,err:%s, adminId:%d", err.Error(), adminId)
  61. return
  62. }
  63. if len(messageList) == 0 {
  64. utils.FileLog.Info("巡检信息历史为空, adminId:%d", adminId)
  65. return
  66. }
  67. readList := make([]int64, 0)
  68. // 消息发送 goroutine
  69. for i, msg := range messageList {
  70. select {
  71. case <-ctx.Done():
  72. return
  73. default:
  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. // 使用互斥锁保护 WebSocket 写操作
  85. wsWriteMutex.Lock()
  86. err = conn.WriteJSON(resp)
  87. if err != nil {
  88. utils.FileLog.Error("巡检信息写通道被锁,消息发送失败,err:%s, adminId:%d", err.Error(), adminId)
  89. wsWriteMutex.Unlock()
  90. continue
  91. }
  92. wsWriteMutex.Unlock()
  93. if err != nil {
  94. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", err.Error(), adminId)
  95. continue
  96. }
  97. utils.FileLog.Info("巡检信息发送成功,adminId:%d, messageId:%d", adminId, msg.MessageId)
  98. readList = append(readList, msg.MessageId)
  99. } else {
  100. readList = append(readList, msg.MessageId)
  101. }
  102. }
  103. }
  104. if len(readList) > 0 {
  105. _, err = data.ReadEdbInspectionMessageList(readList, adminId)
  106. if err != nil {
  107. utils.FileLog.Error("巡检信息已读失败,err:%s, adminId:%d", err.Error(), adminId)
  108. }
  109. }
  110. })
  111. if err != nil {
  112. utils.FileLog.Error("Redis operation failed: %v", err)
  113. continue
  114. }else{
  115. utils.FileLog.Info("巡检信息处理完成, adminId:%d", adminId)
  116. }
  117. }
  118. }
  119. }