websocket_msg.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. package services
  2. import (
  3. "encoding/json"
  4. "eta/eta_api/global"
  5. "eta/eta_api/models"
  6. "eta/eta_api/models/data_manage/edb_inspection"
  7. "eta/eta_api/services/data"
  8. "eta/eta_api/utils"
  9. "fmt"
  10. "runtime"
  11. "sync"
  12. "time"
  13. "context"
  14. )
  15. func DealWebSocketMsg(adminId int) {
  16. DealEdbInspectionMessageTest(adminId)
  17. //go DealEdbInspectionMessage(adminId)
  18. }
  19. // 处理巡检消息
  20. func DealEdbInspectionMessage(adminId int) {
  21. utils.FileLog.Info("创建协程, adminId:%d", adminId)
  22. // 创建上下文用于控制 goroutine 生命周期
  23. ctx, cancel := context.WithCancel(context.Background())
  24. defer cancel()
  25. cacheKey := fmt.Sprintf("%s%d", utils.CACHE_EDB_INSPECTION_MESSAGE, adminId)
  26. // 添加错误恢复机制
  27. defer func() {
  28. if r := recover(); r != nil {
  29. utils.FileLog.Error("WebSocket handler recovered from panic: %v", r)
  30. // 清理资源
  31. cancel()
  32. }
  33. }()
  34. go func() {
  35. ticker := time.NewTicker(time.Minute)
  36. defer ticker.Stop()
  37. for {
  38. select {
  39. case <-ticker.C:
  40. utils.FileLog.Info("Current goroutine count: %d", runtime.NumGoroutine())
  41. case <-ctx.Done():
  42. return
  43. }
  44. }
  45. }()
  46. for {
  47. select {
  48. case <-ctx.Done():
  49. utils.FileLog.Info("DealEdbInspectionMessage 巡检消息处理协程结束, adminId:%d", adminId)
  50. return
  51. default:
  52. // 检查连接状态
  53. conn := global.MonitorMessageConn[adminId]
  54. if conn == nil {
  55. utils.FileLog.Error("检查连接状态 发送消息时发现连接已断开, adminId:%d", adminId)
  56. cancel()
  57. return
  58. }
  59. // 使用带超时的 Redis 操作
  60. val := utils.Rc.Get(cacheKey)
  61. if val == "" {
  62. //utils.FileLog.Info("巡检信息历史为空, adminId:%d", adminId)
  63. continue
  64. }
  65. utils.FileLog.Info("收到巡检信息开始处理, adminId:%d", adminId)
  66. messageList, err := data.GetHistoryInspectionMessages(adminId)
  67. if err != nil {
  68. utils.FileLog.Error("获取巡检信息历史失败,err:%s, adminId:%d", err.Error(), adminId)
  69. return
  70. }
  71. if len(messageList) == 0 {
  72. utils.FileLog.Info("巡检信息历史为空, adminId:%d", adminId)
  73. return
  74. }
  75. readList := make([]int64, 0)
  76. // 检查连接状态
  77. // conn := global.MonitorMessageConn[adminId]
  78. // if conn == nil {
  79. // utils.FileLog.Error("发送消息时发现连接已断开, adminId:%d", adminId)
  80. // cancel()
  81. // return
  82. // }
  83. // 只处理第一条消息的发送,其他消息只标记为已读
  84. for i, msg := range messageList {
  85. if i == 0 {
  86. respData, err := data.SendInspectionMessages(adminId, msg)
  87. if err != nil {
  88. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", err.Error(), adminId)
  89. continue
  90. }
  91. resp := models.WebsocketMessageResponse{
  92. MessageType: 1,
  93. Data: respData,
  94. }
  95. err, isClose := WriteWebSocketMessageAsync(ctx, adminId, resp)
  96. if err != nil {
  97. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", err.Error(), adminId)
  98. cancel()
  99. continue
  100. }
  101. if isClose {
  102. utils.FileLog.Error("巡检信息发送失败,连接已断开, adminId:%d", adminId)
  103. cancel()
  104. return
  105. }
  106. utils.FileLog.Info("巡检信息发送成功,adminId:%d, messageId:%d", adminId, msg.MessageId)
  107. }
  108. readList = append(readList, msg.MessageId)
  109. }
  110. if len(readList) > 0 {
  111. _, err = data.ReadEdbInspectionMessageList(readList, adminId)
  112. if err != nil {
  113. utils.FileLog.Error("巡检信息已读失败,err:%s, adminId:%d", err.Error(), adminId)
  114. }
  115. }
  116. //})
  117. // if err != nil && err.Error() != "redis: nil" {
  118. // utils.FileLog.Error("Redis operation failed: %v", err)
  119. // continue
  120. // }else {
  121. // utils.FileLog.Info("巡检信息处理完成, adminId:%d", adminId)
  122. // }
  123. }
  124. }
  125. }
  126. func WriteWebSocketMessageAsync(ctx context.Context, adminId int, resp interface{}) (error, bool) {
  127. errChan := make(chan error, 1)
  128. var wsWriteMutex sync.Mutex
  129. isClose := false
  130. go func() {
  131. wsWriteMutex.Lock()
  132. defer wsWriteMutex.Unlock()
  133. conn := global.MonitorMessageConn[adminId]
  134. if conn == nil {
  135. isClose = true
  136. errChan <- fmt.Errorf("connection closed for adminId: %d", adminId)
  137. return
  138. }
  139. // 设置写超时
  140. //conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
  141. errChan <- conn.WriteJSON(resp)
  142. }()
  143. select {
  144. case err := <-errChan:
  145. utils.FileLog.Error("WriteWebSocketMessageAsync errChan: %v", err)
  146. return err, isClose
  147. case <-ctx.Done():
  148. utils.FileLog.Error("WriteWebSocketMessageAsync ctx.Done(): %v", ctx.Err())
  149. return ctx.Err(), isClose
  150. }
  151. }
  152. func DealEdbInspectionMessageTest(adminId int) {
  153. messageList, err := data.GetHistoryInspectionMessages(adminId)
  154. if err != nil {
  155. utils.FileLog.Error("获取巡检信息历史失败,err:%s, adminId:%d", err.Error(), adminId)
  156. }
  157. if len(messageList) == 0 {
  158. return
  159. }
  160. go func() {
  161. readList := make([]int64, 0)
  162. for _, msg := range messageList {
  163. // 多条消息仅发送最新一条
  164. respData, err := data.SendInspectionMessages(adminId, msg)
  165. if err != nil {
  166. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", err.Error(), adminId)
  167. return
  168. } else {
  169. resp := models.WebsocketMessageResponse{
  170. MessageType: 1,
  171. Data: respData,
  172. }
  173. conn := global.MonitorMessageConn[adminId]
  174. if conn == nil {
  175. utils.FileLog.Error("巡检信息发送失败,连接已断开, adminId:%d", adminId)
  176. return
  177. }
  178. err = conn.WriteJSON(resp)
  179. if err != nil {
  180. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", err.Error(), adminId)
  181. return
  182. } else {
  183. utils.FileLog.Info("巡检信息发送成功,adminId:%d, messageId:%d", adminId, msg.MessageId)
  184. }
  185. }
  186. readList = append(readList, msg.MessageId)
  187. }
  188. _, err = data.ReadEdbInspectionMessageList(readList, adminId)
  189. if err != nil {
  190. utils.FileLog.Error("巡检信息已读失败,err:%s, adminId:%d", err.Error(), adminId)
  191. return
  192. }
  193. }()
  194. }
  195. func AutoCheckInspectionMessageList() (err error) {
  196. defer func() {
  197. if err != nil {
  198. utils.FileLog.Error("巡检信息发送失败,err:%s", err.Error())
  199. }
  200. }()
  201. ticker := time.NewTicker(time.Second * 10)
  202. defer ticker.Stop()
  203. for {
  204. select {
  205. case <-ticker.C:
  206. err = autoCheckInspectionMessageList()
  207. }
  208. }
  209. }
  210. func autoCheckInspectionMessageList() (err error) {
  211. defer func() {
  212. if err != nil {
  213. utils.FileLog.Error("巡检信息发送失败,err:%s", err.Error())
  214. }
  215. }()
  216. utils.FileLog.Info("检查是否有巡检信息")
  217. admins := make([]int, 0)
  218. for adminId, conn := range global.AdminWebSocketConnMap {
  219. if conn == nil {
  220. continue
  221. }
  222. admins = append(admins, adminId)
  223. }
  224. if len(admins) == 0 {
  225. return
  226. }
  227. messageList, er := edb_inspection.GetUnreadInspectionMessageList(admins)
  228. if er != nil {
  229. err = fmt.Errorf("获取巡检信息历史失败,err:%s", er.Error())
  230. return
  231. }
  232. readList := make([]int64, 0)
  233. for _, msg := range messageList {
  234. adminId := int(msg.AdminId)
  235. respData, er := data.SendInspectionMessages(adminId, msg)
  236. if er != nil {
  237. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", er.Error(), adminId)
  238. } else {
  239. resp := models.WebsocketMessageResponse{
  240. MessageType: 1,
  241. Data: respData,
  242. }
  243. conn := global.AdminWebSocketConnMap[int(msg.AdminId)]
  244. if conn == nil {
  245. utils.FileLog.Error("巡检信息发送失败,连接已断开, adminId:%d", adminId)
  246. return
  247. }
  248. message, er := json.Marshal(resp)
  249. if er != nil {
  250. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", er.Error(), adminId)
  251. return
  252. }
  253. ok := conn.Send(message)
  254. if !ok {
  255. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", adminId)
  256. }
  257. }
  258. readList = append(readList, msg.MessageId)
  259. }
  260. err = edb_inspection.SetEdbInspectionMessageRead(readList)
  261. if err != nil {
  262. err = fmt.Errorf("巡检信息已读失败,err:%s", err.Error())
  263. return
  264. }
  265. return
  266. }