mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-25 02:29:19 +08:00
fix: SSE心跳保活机制,防止后端重启后连接死掉无法感知
后端: - 每15秒向SSE连接发送ping事件 - emitter关闭/超时时取消心跳任务 - 连接断开时自动清理心跳 前端: - 监听ping事件更新lastPingTime - 每5秒检测一次,超过20秒没收到ping则断开重连
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user