websocket_msg.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. }()
  195. }
  196. func AutoCheckWebsocketMessageList() {
  197. ticker := time.NewTicker(time.Second * 10)
  198. defer ticker.Stop()
  199. for {
  200. select {
  201. case <-ticker.C:
  202. // 获取活跃连接
  203. admins := make([]int, 0)
  204. for adminId, conn := range global.AdminWebSocketConnMap {
  205. if conn == nil {
  206. continue
  207. }
  208. admins = append(admins, adminId)
  209. }
  210. // 如果没有活跃连接,继续等待下一个tick
  211. if len(admins) == 0 {
  212. //utils.FileLog.Info("当前没有活跃的WebSocket连接")
  213. continue
  214. }
  215. // 并发处理不同类型的消息
  216. var wg sync.WaitGroup
  217. wg.Add(2)
  218. // 处理巡检消息
  219. go func() {
  220. defer wg.Done()
  221. if err := AutoCheckInspectionMessageList(admins); err != nil {
  222. utils.FileLog.Error("处理巡检消息失败: %v", err)
  223. }
  224. }()
  225. // 处理监控消息
  226. go func() {
  227. defer wg.Done()
  228. if err := edb_monitor.AutoCheckMonitorMessageList(admins); err != nil {
  229. utils.FileLog.Error("处理监控消息失败: %v", err)
  230. }
  231. }()
  232. // 等待所有消息处理完成
  233. wg.Wait()
  234. }
  235. }
  236. }
  237. func AutoCheckInspectionMessageList(admins []int) (err error) {
  238. //utils.FileLog.Info("检查是否有巡检信息")
  239. // 设置redis缓存,防止消息重复处理
  240. cacheKey := fmt.Sprintf("%s", utils.CACHE_EDB_INSPECTION_MESSAGE)
  241. if !utils.Rc.SetNX(cacheKey, 1, 30*time.Second) {
  242. err = fmt.Errorf("系统处理中,请稍后重试!")
  243. utils.FileLog.Error("巡检信息检查失败,err:%s", err.Error())
  244. return
  245. }
  246. defer func() {
  247. _ = utils.Rc.Delete(cacheKey)
  248. }()
  249. messageList, er := edb_inspection.GetUnreadInspectionMessageList(admins)
  250. if er != nil {
  251. err = fmt.Errorf("获取巡检信息历史失败,err:%s", er.Error())
  252. return
  253. }
  254. readList := make([]int64, 0)
  255. for _, msg := range messageList {
  256. adminId := int(msg.AdminId)
  257. respData, er := data.SendInspectionMessages(adminId, msg)
  258. if er != nil {
  259. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", er.Error(), adminId)
  260. } else {
  261. resp := models.WebsocketMessageResponse{
  262. MessageType: 1,
  263. Data: respData,
  264. }
  265. conn := global.AdminWebSocketConnMap[int(msg.AdminId)]
  266. if conn == nil {
  267. utils.FileLog.Error("巡检信息发送失败,连接已断开, adminId:%d", adminId)
  268. return
  269. }
  270. message, er := json.Marshal(resp)
  271. if er != nil {
  272. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", er.Error(), adminId)
  273. return
  274. }
  275. ok := conn.Send(message)
  276. if !ok {
  277. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", adminId)
  278. }
  279. }
  280. readList = append(readList, msg.MessageId)
  281. }
  282. err = edb_inspection.SetEdbInspectionMessageRead(readList)
  283. if err != nil {
  284. err = fmt.Errorf("巡检信息已读失败,err:%s", err.Error())
  285. return
  286. }
  287. return
  288. }
  289. // 弃用
  290. func AutoCheckInspectionMessageListByAdminId(adminId int) (err error) {
  291. defer func() {
  292. if err != nil {
  293. utils.FileLog.Error("巡检信息发送失败,err:%s", err.Error())
  294. }
  295. }()
  296. messageList, er := edb_inspection.GetUnreadInspectionMessageListByAdminId(adminId)
  297. if er != nil {
  298. err = fmt.Errorf("获取巡检信息历史失败,err:%s", er.Error())
  299. return
  300. }
  301. if len(messageList) == 0 {
  302. return
  303. }
  304. readList := make([]int64, 0)
  305. for _, msg := range messageList {
  306. adminId := int(msg.AdminId)
  307. respData, er := data.SendInspectionMessages(adminId, msg)
  308. if er != nil {
  309. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", er.Error(), adminId)
  310. } else {
  311. resp := models.WebsocketMessageResponse{
  312. MessageType: 1,
  313. Data: respData,
  314. }
  315. conn := global.AdminWebSocketConnMap[adminId]
  316. if conn == nil {
  317. utils.FileLog.Error("巡检信息发送失败,连接已断开, adminId:%d", adminId)
  318. return
  319. }
  320. message, er := json.Marshal(resp)
  321. if er != nil {
  322. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", er.Error(), adminId)
  323. return
  324. }
  325. ok := conn.Send(message)
  326. if !ok {
  327. utils.FileLog.Error("巡检信息发送失败,err:%s, adminId:%d", adminId)
  328. }
  329. }
  330. readList = append(readList, msg.MessageId)
  331. }
  332. err = edb_inspection.SetEdbInspectionMessageRead(readList)
  333. if err != nil {
  334. err = fmt.Errorf("巡检信息已读失败,err:%s", err.Error())
  335. return
  336. }
  337. return
  338. }