mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
fix: 修复开发前端代理 sse 断联问题
This commit is contained in:
+41
@@ -0,0 +1,41 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.notify.sse.support;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* SSE 响应头:禁止代理/nginx 缓冲,保证心跳帧能实时推到浏览器。
|
||||
*/
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE + 10)
|
||||
public class SseStreamResponseFilter extends OncePerRequestFilter {
|
||||
|
||||
private static final String SSE_CONNECT_PREFIX = "/api/notify/sse/";
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(@NonNull HttpServletRequest request) {
|
||||
String uri = request.getRequestURI();
|
||||
return uri == null || !uri.startsWith(SSE_CONNECT_PREFIX);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
@NonNull HttpServletRequest request,
|
||||
@NonNull HttpServletResponse response,
|
||||
@NonNull FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
response.setHeader("Cache-Control", "no-cache, no-transform");
|
||||
response.setHeader("Connection", "keep-alive");
|
||||
response.setHeader("X-Accel-Buffering", "no");
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -24,9 +24,65 @@ export const useRealtimeStore = defineStore('realtime', () => {
|
||||
|
||||
let pingCheckTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let visibilityHandler: (() => void) | null = null;
|
||||
/** 单页内复用同一 deviceId,避免重连堆满后端 10 路连接 */
|
||||
let persistentConnection: RealtimeSseConnection | null = null;
|
||||
|
||||
/** 后端 15s 心跳;3 次未收到则重连 */
|
||||
const HEARTBEAT_STALE_MS = 45_000;
|
||||
const HEARTBEAT_CHECK_INTERVAL_MS = 10_000;
|
||||
|
||||
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let started = false;
|
||||
let connecting = false;
|
||||
let internalHandlersBound = false;
|
||||
|
||||
function ensurePersistentConnection(): RealtimeSseConnection {
|
||||
if (!persistentConnection) {
|
||||
persistentConnection = createRealtimeSseConnection();
|
||||
internalHandlersBound = false;
|
||||
}
|
||||
return persistentConnection;
|
||||
}
|
||||
|
||||
/** 内建 connected / error / ping 只绑一次,避免重连重复触发 */
|
||||
function bindInternalHandlers(conn: RealtimeSseConnection) {
|
||||
if (internalHandlersBound) {
|
||||
return;
|
||||
}
|
||||
internalHandlersBound = true;
|
||||
|
||||
const connectedHandler = (event: MessageEvent) => {
|
||||
lastPingTime.value = Date.now();
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.type === 'connected') {
|
||||
connected.value = true;
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
};
|
||||
|
||||
const errorHandler = () => {
|
||||
connected.value = false;
|
||||
scheduleReconnect(3000);
|
||||
};
|
||||
|
||||
conn.addEventListener(RealtimeSseEvent.CONNECTED, connectedHandler);
|
||||
conn.addEventListener('error', errorHandler);
|
||||
conn.addEventListener(RealtimeSseEvent.PING, () => {
|
||||
lastPingTime.value = Date.now();
|
||||
});
|
||||
}
|
||||
|
||||
/** 业务订阅在每次建连时同步到 EventSource */
|
||||
function syncBusinessHandlers(conn: RealtimeSseConnection) {
|
||||
handlers.forEach((set, eventType) => {
|
||||
set.forEach((handler) => {
|
||||
conn.addEventListener(eventType, handler);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function ensureValidToken(): Promise<string | null> {
|
||||
const accessStore = useAccessStore();
|
||||
@@ -48,38 +104,6 @@ export const useRealtimeStore = defineStore('realtime', () => {
|
||||
return accessStore.accessToken;
|
||||
}
|
||||
|
||||
function bindConnectionHandlers(conn: RealtimeSseConnection) {
|
||||
handlers.forEach((set, eventType) => {
|
||||
set.forEach((handler) => {
|
||||
conn.addEventListener(eventType, handler);
|
||||
});
|
||||
});
|
||||
|
||||
const connectedHandler = (event: MessageEvent) => {
|
||||
lastPingTime.value = Date.now();
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.type === 'connected') {
|
||||
connected.value = true;
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
};
|
||||
|
||||
const errorHandler = () => {
|
||||
connected.value = false;
|
||||
// 断线后由我们刷新 token 再连,避免 EventSource 用旧 query token 死循环
|
||||
scheduleReconnect(3000);
|
||||
};
|
||||
|
||||
conn.addEventListener(RealtimeSseEvent.CONNECTED, connectedHandler);
|
||||
conn.addEventListener('error', errorHandler);
|
||||
conn.addEventListener(RealtimeSseEvent.PING, () => {
|
||||
lastPingTime.value = Date.now();
|
||||
});
|
||||
}
|
||||
|
||||
async function connect(): Promise<void> {
|
||||
if (connecting) {
|
||||
return;
|
||||
@@ -98,18 +122,21 @@ export const useRealtimeStore = defineStore('realtime', () => {
|
||||
|
||||
disconnect(false);
|
||||
|
||||
const conn = createRealtimeSseConnection();
|
||||
const conn = ensurePersistentConnection();
|
||||
connection.value = conn;
|
||||
connected.value = false;
|
||||
bindConnectionHandlers(conn);
|
||||
lastPingTime.value = null;
|
||||
bindInternalHandlers(conn);
|
||||
syncBusinessHandlers(conn);
|
||||
conn.connect();
|
||||
|
||||
const HEARTBEAT_STALE_MS = 60_000;
|
||||
lastPingTime.value = Date.now();
|
||||
if (pingCheckTimer !== null) {
|
||||
clearInterval(pingCheckTimer);
|
||||
}
|
||||
pingCheckTimer = setInterval(() => {
|
||||
if (!connected.value) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
lastPingTime.value !== null &&
|
||||
Date.now() - lastPingTime.value > HEARTBEAT_STALE_MS
|
||||
@@ -117,7 +144,7 @@ export const useRealtimeStore = defineStore('realtime', () => {
|
||||
console.warn('[RealtimeSSE] 心跳超时,断开并重连');
|
||||
scheduleReconnect(1000);
|
||||
}
|
||||
}, 10_000);
|
||||
}, HEARTBEAT_CHECK_INTERVAL_MS);
|
||||
|
||||
if (visibilityHandler === null) {
|
||||
visibilityHandler = () => {
|
||||
@@ -178,6 +205,10 @@ export const useRealtimeStore = defineStore('realtime', () => {
|
||||
connection.value.disconnect();
|
||||
connection.value = null;
|
||||
}
|
||||
if (clearVisibility) {
|
||||
persistentConnection = null;
|
||||
internalHandlersBound = false;
|
||||
}
|
||||
connected.value = false;
|
||||
lastPingTime.value = null;
|
||||
}
|
||||
@@ -223,6 +254,8 @@ export const useRealtimeStore = defineStore('realtime', () => {
|
||||
started = false;
|
||||
connecting = false;
|
||||
handlers.clear();
|
||||
internalHandlersBound = false;
|
||||
persistentConnection = null;
|
||||
disconnect(true);
|
||||
}
|
||||
|
||||
|
||||
-5
@@ -464,11 +464,6 @@ defineExpose({ open, close: handleClose });
|
||||
show-icon
|
||||
:message="incremental.lastError"
|
||||
/>
|
||||
<Alert
|
||||
type="info"
|
||||
show-icon
|
||||
message="手动增量按订单更新时间拉取自上次游标以来的变更,用于发货/售后等状态同步。"
|
||||
/>
|
||||
</Space>
|
||||
</Card>
|
||||
|
||||
|
||||
@@ -1,5 +1,33 @@
|
||||
import { defineConfig } from '@vben/vite-config';
|
||||
|
||||
/** 开发环境 SSE 经 Vite 代理时禁止缓冲,否则只有首包 message+ping 后续心跳到不了浏览器 */
|
||||
function configureSseFriendlyProxy(proxyServer: {
|
||||
on: (
|
||||
event: 'proxyReq' | 'proxyRes',
|
||||
listener: (...args: any[]) => void,
|
||||
) => void;
|
||||
}) {
|
||||
proxyServer.on('proxyReq', (proxyReq, req) => {
|
||||
if (req.url?.includes('/notify/sse/')) {
|
||||
proxyReq.setHeader('Accept', 'text/event-stream');
|
||||
proxyReq.setHeader('Cache-Control', 'no-cache');
|
||||
}
|
||||
});
|
||||
proxyServer.on('proxyRes', (proxyRes, req, res) => {
|
||||
const contentType = proxyRes.headers['content-type'];
|
||||
if (
|
||||
req.url?.includes('/notify/sse/') ||
|
||||
(typeof contentType === 'string' &&
|
||||
contentType.includes('text/event-stream'))
|
||||
) {
|
||||
delete proxyRes.headers['content-encoding'];
|
||||
res.setHeader('Cache-Control', 'no-cache, no-transform');
|
||||
res.setHeader('Connection', 'keep-alive');
|
||||
res.setHeader('X-Accel-Buffering', 'no');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export default defineConfig(async () => {
|
||||
return {
|
||||
application: {
|
||||
@@ -18,6 +46,7 @@ export default defineConfig(async () => {
|
||||
// SSE 长连接:禁止代理空闲超时断开
|
||||
timeout: 0,
|
||||
proxyTimeout: 0,
|
||||
configure: configureSseFriendlyProxy,
|
||||
},
|
||||
// 静态资源代理 - 用于访问上传的图片和文件
|
||||
'/uploads': {
|
||||
|
||||
Reference in New Issue
Block a user