session_manager.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. package ws
  2. import (
  3. "errors"
  4. "eta/eta_api/utils"
  5. "fmt"
  6. "github.com/gorilla/websocket"
  7. "sync"
  8. "time"
  9. )
  10. const (
  11. defaultCheckInterval = 20 * time.Second // 检测间隔应小于心跳超时时间
  12. connectionTimeout = 60 * time.Second // 客户端超时时间
  13. )
  14. type ConnectionManager struct {
  15. Sessions sync.Map
  16. ticker *time.Ticker
  17. stopChan chan struct{}
  18. }
  19. var (
  20. smOnce sync.Once
  21. manager *ConnectionManager
  22. )
  23. func GetInstance() *ConnectionManager {
  24. smOnce.Do(func() {
  25. if manager == nil {
  26. manager = &ConnectionManager{
  27. ticker: time.NewTicker(defaultCheckInterval),
  28. stopChan: make(chan struct{}),
  29. }
  30. }
  31. })
  32. return manager
  33. }
  34. func Manager() *ConnectionManager {
  35. return manager
  36. }
  37. // HandleMessage 消息处理核心逻辑
  38. func (manager *ConnectionManager) HandleMessage(userID int, sessionID string, message []byte) error {
  39. if !Allow(userID, QA_LIMITER) {
  40. return errors.New("您提问的太频繁了,请稍后再试")
  41. }
  42. session, exists := manager.GetSession(sessionID)
  43. if !exists {
  44. return errors.New("session not found")
  45. }
  46. // 处理业务逻辑
  47. session.History = append(session.History, string(message))
  48. response := "Processed: " + string(message)
  49. // 更新最后活跃时间
  50. session.LastActive = time.Now()
  51. // 发送响应
  52. return session.Conn.WriteMessage(websocket.TextMessage, []byte(response))
  53. }
  54. // AddSession Add 添加一个新的会话
  55. func (manager *ConnectionManager) AddSession(session *Session) {
  56. manager.Sessions.Store(session.Id, session)
  57. }
  58. func (manager *ConnectionManager) GetSessionId(userId int, sessionId string) (sessionID string) {
  59. return fmt.Sprintf("%d_%s", userId, sessionId)
  60. }
  61. // RemoveSession Remove 移除一个会话
  62. func (manager *ConnectionManager) RemoveSession(sessionCode string) {
  63. manager.Sessions.Delete(sessionCode)
  64. }
  65. // GetSession 获取一个会话
  66. func (manager *ConnectionManager) GetSession(sessionCode string) (session *Session, exists bool) {
  67. if data, ok := manager.Sessions.Load(sessionCode); ok {
  68. session = data.(*Session)
  69. exists = ok
  70. }
  71. return
  72. }
  73. // CheckAll 批量检测所有连接
  74. func (manager *ConnectionManager) CheckAll() {
  75. manager.Sessions.Range(func(key, value interface{}) bool {
  76. fmt.Printf("检测接接:%s", key)
  77. session := value.(*Session)
  78. if session.mu.TryRLock() {
  79. defer session.mu.Unlock()
  80. // 判断超时
  81. if time.Since(session.LastActive) > connectionTimeout {
  82. fmt.Printf("连接超时关闭: SessionID=%s, UserID=%s", session.Id, session.UserId)
  83. utils.FileLog.Warn("连接超时关闭: SessionID=%s, UserID=%s", session.Id, session.UserId)
  84. session.Close()
  85. manager.RemoveSession(session.Id)
  86. return true
  87. }
  88. // 发送心跳
  89. go func(s *Session) {
  90. err := s.Conn.WriteControl(websocket.PingMessage,
  91. nil, time.Now().Add(5*time.Second))
  92. fmt.Printf(s.Id)
  93. if err != nil {
  94. fmt.Printf("心跳发送失败: SessionID=%s, Error=%v", s.Id, err)
  95. utils.FileLog.Warn("心跳发送失败: SessionID=%s, Error=%v",
  96. s.Id, err)
  97. session.Close()
  98. manager.RemoveSession(s.Id)
  99. }
  100. }(session)
  101. return true
  102. }
  103. return true
  104. })
  105. }
  106. // Start 启动心跳检测
  107. func (manager *ConnectionManager) Start() {
  108. defer manager.ticker.Stop()
  109. for {
  110. select {
  111. case <-manager.ticker.C:
  112. manager.CheckAll()
  113. case <-manager.stopChan:
  114. return
  115. }
  116. }
  117. }
  118. // Stop 停止心跳检测
  119. func (manager *ConnectionManager) Stop() {
  120. close(manager.stopChan)
  121. }