Files
gjs 0d8cfc695c
CI / changes (push) Successful in 1m31s
CI / ad (push) Successful in 32s
CI / admin (push) Successful in 22s
CI / bff (push) Successful in 19s
CI / chore (push) Successful in 18s
CI / equipment (push) Successful in 19s
CI / express (push) Successful in 18s
CI / factory (push) Successful in 17s
CI / message (push) Successful in 18s
CI / order (push) Successful in 17s
CI / payment (push) Successful in 17s
CI / percutaneous (push) Successful in 17s
CI / product (push) Successful in 17s
CI / record (push) Successful in 9m26s
CI / sale (push) Successful in 45s
CI / support (push) Successful in 3m8s
CI / task (push) Successful in 27s
CI / user (push) Successful in 21s
CI / wecom (push) Successful in 19s
ws
2026-10-08 16:37:33 +08:00

66 lines
1.4 KiB
Go

package utils
import (
"context"
"sync"
"github.com/zeromicro/go-zero/core/logx"
)
// Stream 通用双向流抽象接口
type Stream interface {
Send(payload []byte) error
}
// WaitingSession 通用等待会话
type WaitingSession struct {
Stream Stream
Ctx context.Context
Cancel context.CancelFunc
MsgCh chan []byte
}
// WsSessionManager 会话管理器
type WsSessionManager struct {
mu sync.RWMutex
sessions map[string]*WaitingSession // key: deviceCode
}
// 全局单例,logic直接用 WsSessionMgr
var WsSessionMgr = NewWsSessionManager()
func NewWsSessionManager() *WsSessionManager {
return &WsSessionManager{
sessions: make(map[string]*WaitingSession),
}
}
// Register 注册会话
func (m *WsSessionManager) Register(deviceCode string, sess *WaitingSession) {
m.mu.Lock()
defer m.mu.Unlock()
m.sessions[deviceCode] = sess
logx.Infof("register ws session, deviceCode=%s", deviceCode)
}
// Pop 取出并删除会话
func (m *WsSessionManager) Pop(deviceCode string) *WaitingSession {
m.mu.Lock()
defer m.mu.Unlock()
sess, ok := m.sessions[deviceCode]
if !ok {
return nil
}
delete(m.sessions, deviceCode)
logx.Infof("pop ws session, deviceCode=%s", deviceCode)
return sess
}
// Remove 移除会话
func (m *WsSessionManager) Remove(deviceCode string) {
m.mu.Lock()
defer m.mu.Unlock()
delete(m.sessions, deviceCode)
logx.Infof("remove ws session, deviceCode=%s", deviceCode)
}