feat: 增强SignalR连接管理,添加重连机制和状态提示
- 实现自定义重连策略,支持最大重连次数限制 - 添加连接丢失和恢复的处理函数 - 显示重连状态和服务不可用提示 - 优化心跳机制和页面可见性下的连接管理
This commit is contained in:
1 parent
c38199268f
commit
e3002cabf6
1 file changed
+150
-10
@@ -6,18 +6,34 @@
|
|||||||
var heartbeatTimer = null;
|
var heartbeatTimer = null;
|
||||||
var userId = '@ViewData["ITCode"]'; // 从后端获取当前用户ID
|
var userId = '@ViewData["ITCode"]'; // 从后端获取当前用户ID
|
||||||
var isForceLogout = false;
|
var isForceLogout = false;
|
||||||
|
|
||||||
|
// 服务异常检测
|
||||||
|
var reconnectAttempts = 0; // 重连尝试次数
|
||||||
|
var maxReconnectAttempts = 5; // 最大重连次数
|
||||||
|
var isServerDown = false; // 服务是否宕机
|
||||||
|
var serverDownAlertIndex = null; // 服务宕机弹窗索引
|
||||||
|
var reconnectTimer = null; // 重连定时器
|
||||||
|
|
||||||
// 初始化 SignalR 连接
|
// 初始化 SignalR 连接
|
||||||
function initLoginHub() {
|
function initLoginHub() {
|
||||||
loginConnection = new signalR.HubConnectionBuilder()
|
loginConnection = new signalR.HubConnectionBuilder()
|
||||||
.withUrl("/loginHub")
|
.withUrl("/loginHub")
|
||||||
.withAutomaticReconnect([0, 2000, 5000, 10000, 30000]) // 自动重连策略
|
.withAutomaticReconnect({
|
||||||
|
nextRetryDelayInMilliseconds: function(retryContext) {
|
||||||
|
// 自定义重连策略
|
||||||
|
if (retryContext.previousRetryCount < maxReconnectAttempts) {
|
||||||
|
return Math.min(1000 * Math.pow(2, retryContext.previousRetryCount), 30000);
|
||||||
|
}
|
||||||
|
return null; // 停止自动重连
|
||||||
|
}
|
||||||
|
})
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
// 监听强制登出事件
|
// 监听强制登出事件
|
||||||
loginConnection.on("ForceLogout", function(message) {
|
loginConnection.on("ForceLogout", function(message) {
|
||||||
isForceLogout = true;
|
isForceLogout = true;
|
||||||
stopHeartbeat();
|
stopHeartbeat();
|
||||||
|
stopReconnect();
|
||||||
|
|
||||||
// 使用layer弹窗提示
|
// 使用layer弹窗提示
|
||||||
layer.alert(message || "您的账号已在其他设备登录,请重新登录", {
|
layer.alert(message || "您的账号已在其他设备登录,请重新登录", {
|
||||||
@@ -36,6 +52,7 @@
|
|||||||
// 监听注册成功
|
// 监听注册成功
|
||||||
loginConnection.on("RegisterSuccess", function(message) {
|
loginConnection.on("RegisterSuccess", function(message) {
|
||||||
console.log("SignalR 登录连接成功:", message);
|
console.log("SignalR 登录连接成功:", message);
|
||||||
|
onConnectionRestored();
|
||||||
startHeartbeat();
|
startHeartbeat();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -50,16 +67,21 @@
|
|||||||
stopHeartbeat();
|
stopHeartbeat();
|
||||||
|
|
||||||
if (!isForceLogout) {
|
if (!isForceLogout) {
|
||||||
// 非强制登出,尝试重连
|
onConnectionLost();
|
||||||
setTimeout(function() {
|
|
||||||
startConnection();
|
|
||||||
}, 5000);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 正在重连事件
|
||||||
|
loginConnection.onreconnecting(function(error) {
|
||||||
|
console.log("SignalR 正在重连...", error);
|
||||||
|
reconnectAttempts++;
|
||||||
|
showReconnectingStatus();
|
||||||
|
});
|
||||||
|
|
||||||
// 重连成功事件
|
// 重连成功事件
|
||||||
loginConnection.onreconnected(function(connectionId) {
|
loginConnection.onreconnected(function(connectionId) {
|
||||||
console.log("SignalR 重连成功:", connectionId);
|
console.log("SignalR 重连成功:", connectionId);
|
||||||
|
onConnectionRestored();
|
||||||
// 重新注册
|
// 重新注册
|
||||||
if (userId) {
|
if (userId) {
|
||||||
loginConnection.invoke("Register", userId).catch(function(err) {
|
loginConnection.invoke("Register", userId).catch(function(err) {
|
||||||
@@ -79,6 +101,7 @@
|
|||||||
loginConnection.start()
|
loginConnection.start()
|
||||||
.then(function() {
|
.then(function() {
|
||||||
console.log("SignalR 连接已建立");
|
console.log("SignalR 连接已建立");
|
||||||
|
onConnectionRestored();
|
||||||
// 注册当前用户
|
// 注册当前用户
|
||||||
if (userId) {
|
if (userId) {
|
||||||
loginConnection.invoke("Register", userId).catch(function(err) {
|
loginConnection.invoke("Register", userId).catch(function(err) {
|
||||||
@@ -88,13 +111,126 @@
|
|||||||
})
|
})
|
||||||
.catch(function(err) {
|
.catch(function(err) {
|
||||||
console.error("SignalR 连接失败:", err);
|
console.error("SignalR 连接失败:", err);
|
||||||
// 连接失败,5秒后重试
|
reconnectAttempts++;
|
||||||
setTimeout(function() {
|
|
||||||
startConnection();
|
if (reconnectAttempts >= maxReconnectAttempts) {
|
||||||
}, 5000);
|
// 达到最大重连次数,显示服务不可用
|
||||||
|
showServerDownAlert();
|
||||||
|
} else {
|
||||||
|
// 继续重连
|
||||||
|
showReconnectingStatus();
|
||||||
|
var delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000);
|
||||||
|
reconnectTimer = setTimeout(function() {
|
||||||
|
startConnection();
|
||||||
|
}, delay);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 连接丢失处理
|
||||||
|
function onConnectionLost() {
|
||||||
|
reconnectAttempts = 0;
|
||||||
|
showReconnectingStatus();
|
||||||
|
|
||||||
|
// 手动启动重连
|
||||||
|
reconnectTimer = setTimeout(function() {
|
||||||
|
startConnection();
|
||||||
|
}, 2000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 连接恢复处理
|
||||||
|
function onConnectionRestored() {
|
||||||
|
reconnectAttempts = 0;
|
||||||
|
isServerDown = false;
|
||||||
|
hideReconnectingStatus();
|
||||||
|
hideServerDownAlert();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 显示重连中状态
|
||||||
|
function showReconnectingStatus() {
|
||||||
|
if ($('#reconnecting-status').length === 0) {
|
||||||
|
$('body').append(
|
||||||
|
'<div id="reconnecting-status" style="position:fixed;top:0;left:0;right:0;background:#ff9800;color:#fff;text-align:center;padding:8px;z-index:99999;font-size:14px;">' +
|
||||||
|
'<i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i> ' +
|
||||||
|
'正在连接服务器... (尝试 ' + reconnectAttempts + '/' + maxReconnectAttempts + ')' +
|
||||||
|
'</div>'
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
$('#reconnecting-status').html(
|
||||||
|
'<i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i> ' +
|
||||||
|
'正在连接服务器... (尝试 ' + reconnectAttempts + '/' + maxReconnectAttempts + ')'
|
||||||
|
).show();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 隐藏重连中状态
|
||||||
|
function hideReconnectingStatus() {
|
||||||
|
$('#reconnecting-status').hide();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 显示服务不可用弹窗
|
||||||
|
function showServerDownAlert() {
|
||||||
|
if (isServerDown) return;
|
||||||
|
isServerDown = true;
|
||||||
|
hideReconnectingStatus();
|
||||||
|
|
||||||
|
// 显示服务不可用状态栏
|
||||||
|
if ($('#server-down-status').length === 0) {
|
||||||
|
$('body').append(
|
||||||
|
'<div id="server-down-status" style="position:fixed;top:0;left:0;right:0;background:#f44336;color:#fff;text-align:center;padding:8px;z-index:99999;font-size:14px;">' +
|
||||||
|
'<i class="layui-icon layui-icon-close-fill"></i> ' +
|
||||||
|
'服务器连接已断开,请检查网络或联系管理员 ' +
|
||||||
|
'<button onclick="manualReconnect()" style="margin-left:10px;padding:2px 10px;cursor:pointer;background:#fff;color:#f44336;border:none;border-radius:3px;">重新连接</button>' +
|
||||||
|
'</div>'
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
$('#server-down-status').show();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 弹窗提示
|
||||||
|
if (!serverDownAlertIndex) {
|
||||||
|
serverDownAlertIndex = layer.confirm('服务器连接已断开,可能是网络问题或服务器维护中。<br/>是否重新连接?', {
|
||||||
|
icon: 2,
|
||||||
|
title: "连接异常",
|
||||||
|
btn: ['重新连接', '稍后再试'],
|
||||||
|
closeBtn: 0
|
||||||
|
}, function(index) {
|
||||||
|
layer.close(index);
|
||||||
|
serverDownAlertIndex = null;
|
||||||
|
manualReconnect();
|
||||||
|
}, function(index) {
|
||||||
|
layer.close(index);
|
||||||
|
serverDownAlertIndex = null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 隐藏服务不可用弹窗
|
||||||
|
function hideServerDownAlert() {
|
||||||
|
$('#server-down-status').hide();
|
||||||
|
if (serverDownAlertIndex) {
|
||||||
|
layer.close(serverDownAlertIndex);
|
||||||
|
serverDownAlertIndex = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 手动重连
|
||||||
|
function manualReconnect() {
|
||||||
|
reconnectAttempts = 0;
|
||||||
|
isServerDown = false;
|
||||||
|
hideServerDownAlert();
|
||||||
|
showReconnectingStatus();
|
||||||
|
startConnection();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 停止重连
|
||||||
|
function stopReconnect() {
|
||||||
|
if (reconnectTimer) {
|
||||||
|
clearTimeout(reconnectTimer);
|
||||||
|
reconnectTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 开始心跳
|
// 开始心跳
|
||||||
function startHeartbeat() {
|
function startHeartbeat() {
|
||||||
stopHeartbeat();
|
stopHeartbeat();
|
||||||
@@ -123,6 +259,8 @@
|
|||||||
|
|
||||||
// 页面关闭时断开连接
|
// 页面关闭时断开连接
|
||||||
$(window).on('beforeunload', function() {
|
$(window).on('beforeunload', function() {
|
||||||
|
stopReconnect();
|
||||||
|
stopHeartbeat();
|
||||||
if (loginConnection) {
|
if (loginConnection) {
|
||||||
loginConnection.stop();
|
loginConnection.stop();
|
||||||
}
|
}
|
||||||
@@ -132,7 +270,9 @@
|
|||||||
$(document).on('visibilitychange', function() {
|
$(document).on('visibilitychange', function() {
|
||||||
if (document.visibilityState === 'visible' && !isForceLogout) {
|
if (document.visibilityState === 'visible' && !isForceLogout) {
|
||||||
if (loginConnection && loginConnection.state !== signalR.HubConnectionState.Connected) {
|
if (loginConnection && loginConnection.state !== signalR.HubConnectionState.Connected) {
|
||||||
startConnection();
|
if (!isServerDown) {
|
||||||
|
manualReconnect();
|
||||||
|
}
|
||||||
} else if (loginConnection && userId) {
|
} else if (loginConnection && userId) {
|
||||||
// 页面可见时发送一次心跳
|
// 页面可见时发送一次心跳
|
||||||
loginConnection.invoke("Heartbeat", userId).catch(function(err) {
|
loginConnection.invoke("Heartbeat", userId).catch(function(err) {
|
||||||
|
|||||||
Reference in new issue
Block a user