fix: SSE心跳保活机制,防止后端重启后连接死掉无法感知

后端:
- 每15秒向SSE连接发送ping事件
- emitter关闭/超时时取消心跳任务
- 连接断开时自动清理心跳

前端:
- 监听ping事件更新lastPingTime
- 每5秒检测一次,超过20秒没收到ping则断开重连
This commit is contained in:
小蟑螂
2026-04-16 13:43:11 +08:00
parent ae16f6ab06
commit 2b35471deb
3 changed files with 112 additions and 7 deletions
@@ -29,6 +29,9 @@ export const useImportTaskStore = defineStore('import-task', () => {
null,
);
const sseConnected = ref(false);
// 心跳检测:上次收到ping的时间
const lastPingTime = ref<number | null>(null);
let pingCheckTimer: ReturnType<typeof setInterval> | null = null;
// 加载状态
const loading = ref(false);
@@ -165,6 +168,21 @@ export const useImportTaskStore = defineStore('import-task', () => {
connection.connect();
// 启动心跳检测:每5秒检查一次,超过20秒没收到ping则断开重连
lastPingTime.value = Date.now();
if (pingCheckTimer !== null) {
clearInterval(pingCheckTimer);
}
pingCheckTimer = setInterval(() => {
if (lastPingTime.value !== null && Date.now() - lastPingTime.value > 20_000) {
console.warn('SSE心跳超时,断开并重连');
disconnectSse();
setTimeout(() => {
connectSse();
}, 1000);
}
}, 5_000);
// 连接成功(如果不在等待连接,则正常处理)
connection.addEventListener('message', (event) => {
try {
@@ -177,6 +195,11 @@ export const useImportTaskStore = defineStore('import-task', () => {
}
});
// 接收心跳ping
connection.addEventListener('ping', () => {
lastPingTime.value = Date.now();
});
// 接收任务进度更新
connection.addEventListener('task_progress', (event) => {
try {
@@ -226,6 +249,11 @@ export const useImportTaskStore = defineStore('import-task', () => {
sseConnection.value.disconnect();
sseConnection.value = null;
sseConnected.value = false;
lastPingTime.value = null;
}
if (pingCheckTimer !== null) {
clearInterval(pingCheckTimer);
pingCheckTimer = null;
}
}