websocket_msg.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. edb_monitor "eta/eta_api/services/edb_monitor"
  9. "eta/eta_api/utils"
  10. "fmt"
  11. "runtime"
  12. "sync"
  13. "time"
  14. "context"
  15. )
  16. func DealWebSocketMsg(adminId int) {
  17. DealEdbInspectionMessageTest(adminId)
  18. //go DealEdbInspectionMessage(adminId)
  19. }
  20. // 处理巡检消息
  21. func DealEdbInspectionMessage(adminId int) {
  22. utils.FileLog.Info("创建协程, adminId:%d", adminId)
  23. // 创建上下文用于控制 goroutine 生命周期
  24. ctx, cancel := context.WithCancel(context.Background())
  25. defer cancel()
  26. cacheKey := fmt.Sprintf("%s%d", utils.CACHE_EDB_INSPECTION_MESSAGE, adminId)
  27. // 添加错误恢复机制
  28. defer func() {
  29. if r := recover(); r != nil {
  30. utils.FileLog.Error("WebSocket handler recovered from panic: %v", r)
  31. // 清理资源
  32. cancel()
  33. }
  34. }()
  35. go func() {
  36. ticker := time.NewTicker(time.Minute)
  37. defer ticker.Stop()
  38. for {
  39. select {
  40. case <-ticker.C:
  41. utils.FileLog.Info("Current goroutine count: %d", runtime.NumGoroutine())
  42. case <-ctx.Done():
  43. return
  44. }
  45. }
  46. }()
  47. for {
  48. select {
  49. case <-ctx.Done():
  50. utils.FileLog.Info("DealEdbInspectionMessage 巡检消息处理协程结束, adminId:%d", adminId)
  51. return
  52. default:
  53. // 检查连接状态
  54. conn := global.MonitorMessageConn[adminId]
  55. if conn == nil {
  56. utils.FileLog.Error("检查连接状态 发送消息时发现连接已断开, adminId:%d", adminId)
  57. cancel()
  58. return
  59. }
  60. // 使用带超时的 Redis 操作
  61. val := utils.Rc.Get(cacheKey)
  62. if val == "" {
  63. //utils.FileLog.Info("巡检信息历史为空, adminId:%d", adminId)
  64. continue
  65. }
  66. utils.FileLog.Info("收到巡检信息开始处理, adminId:%d", adminId)
  67. messageList, err := data.GetHistoryInspectionMessages(adminId)
  68. if err != nil {
  69. utils.FileLog.Error("获取巡检信息历史失败,err:%s, adminId:%d", err.Error(), adminId)
  70. return
  71. }
  72. if len(messageList) == 0 {
  73. utils.FileLog.Info("巡检信息历史为空, adminId:%d", adminId)
  74. return
  75. }
  76. readList := make([]int64, 0)
  77. // 检查连接状态
  78. // conn := global.MonitorMessageConn[adminId]
  79. // if conn == nil {
  80. // utils.FileLog.Error("发送消息时发现连接已断开, adminId:%d", adminId)
  81. // cancel()
  82. // return
  83. // }
  84. // 只处理第一条消息的发送,其他消息只标记为已读
  85. for i, msg := range messageList {
  86. if i == 0 {
  87. respData, err := data.SendInspectionMessages(adminId, msg)
  88. if err != nil {
  89. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", err.Error(), adminId)
  90. continue
  91. }
  92. resp := models.WebsocketMessageResponse{
  93. MessageType: 1,
  94. Data: respData,
  95. }
  96. err, isClose := WriteWebSocketMessageAsync(ctx, adminId, resp)
  97. if err != nil {
  98. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", err.Error(), adminId)
  99. cancel()
  100. continue
  101. }
  102. if isClose {
  103. utils.FileLog.Error("巡检信息发送失败,连接已断开, adminId:%d", adminId)
  104. cancel()
  105. return
  106. }
  107. utils.FileLog.Info("巡检信息发送成功,adminId:%d, messageId:%d", adminId, msg.MessageId)
  108. }
  109. readList = append(readList, msg.MessageId)
  110. }
  111. if len(readList) > 0 {
  112. _, err = data.ReadEdbInspectionMessageList(readList, adminId)
  113. if err != nil {
  114. utils.FileLog.Error("巡检信息已读失败,err:%s, adminId:%d", err.Error(), adminId)
  115. }
  116. }
  117. //})
  118. // if err != nil && err.Error() != "redis: nil" {
  119. // utils.FileLog.Error("Redis operation failed: %v", err)
  120. // continue
  121. // }else {
  122. // utils.FileLog.Info("巡检信息处理完成, adminId:%d", adminId)
  123. // }
  124. }
  125. }
  126. }
  127. func WriteWebSocketMessageAsync(ctx context.Context, adminId int, resp interface{}) (error, bool) {
  128. errChan := make(chan error, 1)
  129. var wsWriteMutex sync.Mutex
  130. isClose := false
  131. go func() {
  132. wsWriteMutex.Lock()
  133. defer wsWriteMutex.Unlock()
  134. conn := global.MonitorMessageConn[adminId]
  135. if conn == nil {
  136. isClose = true
  137. errChan <- fmt.Errorf("connection closed for adminId: %d", adminId)
  138. return
  139. }
  140. // 设置写超时
  141. //conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
  142. errChan <- conn.WriteJSON(resp)
  143. }()
  144. select {
  145. case err := <-errChan:
  146. utils.FileLog.Error("WriteWebSocketMessageAsync errChan: %v", err)
  147. return err, isClose
  148. case <-ctx.Done():
  149. utils.FileLog.Error("WriteWebSocketMessageAsync ctx.Done(): %v", ctx.Err())
  150. return ctx.Err(), isClose
  151. }
  152. }
  153. func DealEdbInspectionMessageTest(adminId int) {
  154. messageList, err := data.GetHistoryInspectionMessages(adminId)
  155. if err != nil {
  156. utils.FileLog.Error("获取巡检信息历史失败,err:%s, adminId:%d", err.Error(), adminId)
  157. }
  158. if len(messageList) == 0 {
  159. return
  160. }
  161. go func() {
  162. readList := make([]int64, 0)
  163. for _, msg := range messageList {
  164. // 多条消息仅发送最新一条
  165. respData, err := data.SendInspectionMessages(adminId, msg)
  166. if err != nil {
  167. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", err.Error(), adminId)
  168. return
  169. } else {
  170. resp := models.WebsocketMessageResponse{
  171. MessageType: 1,
  172. Data: respData,
  173. }
  174. conn := global.MonitorMessageConn[adminId]
  175. if conn == nil {
  176. utils.FileLog.Error("巡检信息发送失败,连接已断开, adminId:%d", adminId)
  177. return
  178. }
  179. err = conn.WriteJSON(resp)
  180. if err != nil {
  181. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", err.Error(), adminId)
  182. return
  183. } else {
  184. utils.FileLog.Info("巡检信息发送成功,adminId:%d, messageId:%d", adminId, msg.MessageId)
  185. }
  186. }
  187. readList = append(readList, msg.MessageId)
  188. }
  189. _, err = data.ReadEdbInspectionMessageList(readList, adminId)
  190. if err != nil {
  191. utils.FileLog.Error("巡检信息已读失败,err:%s, adminId:%d", err.Error(), adminId)
  192. return
  193. }
  194. _, err = data.ReadEdbInspectionMessageList(readList, adminId)
  195. if err != nil {
  196. utils.FileLog.Error("巡检信息已读失败,err:%s, adminId:%d", err.Error(), adminId)
  197. }
  198. }()
  199. }
  200. func AutoCheckWebsocketMessageList() {
  201. ticker := time.NewTicker(time.Second * 10)
  202. defer ticker.Stop()
  203. for {
  204. select {
  205. case <-ticker.C:
  206. // 获取活跃连接
  207. admins := make([]int, 0)
  208. for adminId, conn := range global.AdminWebSocketConnMap {
  209. if conn == nil {
  210. continue
  211. }
  212. admins = append(admins, adminId)
  213. }
  214. // 如果没有活跃连接,继续等待下一个tick
  215. if len(admins) == 0 {
  216. //utils.FileLog.Info("当前没有活跃的WebSocket连接")
  217. continue
  218. }
  219. // 并发处理不同类型的消息
  220. var wg sync.WaitGroup
  221. wg.Add(2)
  222. // 处理巡检消息
  223. go func() {
  224. defer wg.Done()
  225. if err := AutoCheckInspectionMessageList(admins); err != nil {
  226. utils.FileLog.Error("处理巡检消息失败: %v", err)
  227. }
  228. }()
  229. // 处理监控消息
  230. go func() {
  231. defer wg.Done()
  232. if err := edb_monitor.AutoCheckMonitorMessageList(admins); err != nil {
  233. utils.FileLog.Error("处理监控消息失败: %v", err)
  234. }
  235. }()
  236. // 等待所有消息处理完成
  237. wg.Wait()
  238. }
  239. }
  240. }
  241. func AutoCheckInspectionMessageList(admins []int) (err error) {
  242. //utils.FileLog.Info("检查是否有巡检信息")
  243. // 设置redis缓存,防止消息重复处理
  244. cacheKey := fmt.Sprintf("%s", utils.CACHE_EDB_INSPECTION_MESSAGE)
  245. if !utils.Rc.SetNX(cacheKey, 1, 30*time.Second) {
  246. err = fmt.Errorf("系统处理中,请稍后重试!")
  247. utils.FileLog.Error("巡检信息检查失败,err:%s", err.Error())
  248. return
  249. }
  250. defer func() {
  251. _ = utils.Rc.Delete(cacheKey)
  252. }()
  253. messageList, er := edb_inspection.GetUnreadInspectionMessageList(admins)
  254. if er != nil {
  255. err = fmt.Errorf("获取巡检信息历史失败,err:%s", er.Error())
  256. return
  257. }
  258. readList := make([]int64, 0)
  259. for _, msg := range messageList {
  260. adminId := int(msg.AdminId)
  261. respData, er := data.SendInspectionMessages(adminId, msg)
  262. if er != nil {
  263. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", er.Error(), adminId)
  264. } else {
  265. resp := models.WebsocketMessageResponse{
  266. MessageType: 1,
  267. Data: respData,
  268. }
  269. conn := global.AdminWebSocketConnMap[int(msg.AdminId)]
  270. if conn == nil {
  271. utils.FileLog.Error("巡检信息发送失败,连接已断开, adminId:%d", adminId)
  272. return
  273. }
  274. message, er := json.Marshal(resp)
  275. if er != nil {
  276. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", er.Error(), adminId)
  277. return
  278. }
  279. ok := conn.Send(message)
  280. if !ok {
  281. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", adminId)
  282. }
  283. }
  284. readList = append(readList, msg.MessageId)
  285. }
  286. err = edb_inspection.SetEdbInspectionMessageRead(readList)
  287. if err != nil {
  288. err = fmt.Errorf("巡检信息已读失败,err:%s", err.Error())
  289. return
  290. }
  291. return
  292. }
  293. // 弃用
  294. func AutoCheckInspectionMessageListByAdminId(adminId int) (err error) {
  295. defer func() {
  296. if err != nil {
  297. utils.FileLog.Error("巡检信息发送失败,err:%s", err.Error())
  298. }
  299. }()
  300. messageList, er := edb_inspection.GetUnreadInspectionMessageListByAdminId(adminId)
  301. if er != nil {
  302. err = fmt.Errorf("获取巡检信息历史失败,err:%s", er.Error())
  303. return
  304. }
  305. if len(messageList) == 0 {
  306. return
  307. }
  308. readList := make([]int64, 0)
  309. for _, msg := range messageList {
  310. adminId := int(msg.AdminId)
  311. respData, er := data.SendInspectionMessages(adminId, msg)
  312. if er != nil {
  313. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", er.Error(), adminId)
  314. } else {
  315. resp := models.WebsocketMessageResponse{
  316. MessageType: 1,
  317. Data: respData,
  318. }
  319. conn := global.AdminWebSocketConnMap[adminId]
  320. if conn == nil {
  321. utils.FileLog.Error("巡检信息发送失败,连接已断开, adminId:%d", adminId)
  322. return
  323. }
  324. message, er := json.Marshal(resp)
  325. if er != nil {
  326. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", er.Error(), adminId)
  327. return
  328. }
  329. ok := conn.Send(message)
  330. if !ok {
  331. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", adminId)
  332. }
  333. }
  334. readList = append(readList, msg.MessageId)
  335. }
  336. err = edb_inspection.SetEdbInspectionMessageRead(readList)
  337. if err != nil {
  338. err = fmt.Errorf("巡检信息已读失败,err:%s", err.Error())
  339. return
  340. }
  341. return
  342. }