useSse SSE 连接
SSE(Server-Sent Events)长连接管理,用于与后端建立实时通信通道。
基础用法
typescript
import { useSse } from '@/composables'
const { isConnected, connect, disconnect, on } = useSse()
// 建立连接(登录后调用)
onMounted(() => {
connect()
})
// 订阅事件
const unsubscribe = on('dict-change', (data) => {
console.log('字典已更新:', data)
})
// 取消订阅
onUnmounted(() => {
unsubscribe()
})
// 断开连接(登出时调用)
disconnect()配置选项
typescript
interface UseSseOptions {
url?: string // SSE 连接地址,默认走 VITE_APP_BASE_API 代理
debug?: boolean // 是否打印调试日志
connectionTimeout?: number // 连接超时(ms),默认 10000
reconnectInterval?: number // 重连间隔基数(ms),默认 5000
maxReconnectInterval?: number // 重连间隔上限(ms),默认 120000
maxReconnectAttempts?: number // 最大重试次数,默认 10
}返回值
| 属性/方法 | 类型 | 说明 |
|---|---|---|
connectionState | Readonly<Ref<SseConnectionState>> | 连接状态 |
isConnected | ComputedRef<boolean> | 是否已连接 |
connect | () => void | 建立连接 |
disconnect | () => void | 断开连接(不触发重连) |
cleanup | () => void | 清理资源(登出时调用) |
on | (event, handler) => () => void | 订阅事件,返回取消函数 |
typescript
enum SseConnectionState {
DISCONNECTED = 'DISCONNECTED',
CONNECTING = 'CONNECTING',
CONNECTED = 'CONNECTED',
}自动重连策略
采用指数退避,重连成功后计数器重置:
| 重试次数 | 等待时间 |
|---|---|
| 1 | 5s |
| 2 | 10s |
| 3 | 20s |
| 4 | 40s |
| 5 | 80s |
| 6+ | 120s(上限) |
环境配置
bash
# .env.development(开发环境走代理)
VITE_APP_BASE_API=http://localhost:8080
# SSE 连接地址自动拼接为:
# http://localhost:8080/api/v1/sse/connect自定义地址:
typescript
useSse({ url: 'https://api.example.com/custom-sse-endpoint' })单例模式
多次调用 useSse() 返回同一实例。连接前需确保已登录,否则连接被跳过;登出时调用 cleanup() 释放资源。
