feat: 重构signalr,在线人数允许不用登录
This commit is contained in:
@@ -9,7 +9,8 @@ using Yi.Framework.Rbac.Domain.Shared.Model;
|
|||||||
namespace Yi.Framework.Rbac.Application.SignalRHubs
|
namespace Yi.Framework.Rbac.Application.SignalRHubs
|
||||||
{
|
{
|
||||||
[HubRoute("/hub/main")]
|
[HubRoute("/hub/main")]
|
||||||
[Authorize]
|
//开放不需要授权
|
||||||
|
//[Authorize]
|
||||||
public class OnlineHub : AbpHub
|
public class OnlineHub : AbpHub
|
||||||
{
|
{
|
||||||
public static readonly List<OnlineUserModel> clientUsers = new();
|
public static readonly List<OnlineUserModel> clientUsers = new();
|
||||||
@@ -32,33 +33,32 @@ namespace Yi.Framework.Rbac.Application.SignalRHubs
|
|||||||
{
|
{
|
||||||
lock (objLock)
|
lock (objLock)
|
||||||
{
|
{
|
||||||
|
|
||||||
var name = CurrentUser.UserName;
|
var name = CurrentUser.UserName;
|
||||||
var loginUser = new LoginLogEntity().GetInfoByHttpContext(_httpContext);
|
var loginUser = new LoginLogEntity().GetInfoByHttpContext(_httpContext);
|
||||||
var user = clientUsers.Any(u => u is not null && u.ConnnectionId == Context.ConnectionId);
|
|
||||||
//判断用户是否存在,否则添加集合
|
OnlineUserModel user = new(Context.ConnectionId)
|
||||||
if (!user)
|
|
||||||
{
|
{
|
||||||
OnlineUserModel users = new(Context.ConnectionId)
|
Browser = loginUser?.Browser,
|
||||||
{
|
LoginLocation = loginUser?.LoginLocation,
|
||||||
Browser = loginUser?.Browser,
|
Ipaddr = loginUser?.LoginIp,
|
||||||
LoginLocation = loginUser?.LoginLocation,
|
LoginTime = DateTime.Now,
|
||||||
Ipaddr = loginUser?.LoginIp,
|
Os = loginUser?.Os,
|
||||||
LoginTime = DateTime.Now,
|
UserName = name ?? "Null",
|
||||||
Os = loginUser?.Os,
|
UserId = CurrentUser.Id ?? Guid.Empty
|
||||||
UserName = name ?? "Null",
|
};
|
||||||
UserId = CurrentUser.Id ?? Guid.Empty
|
|
||||||
};
|
|
||||||
|
|
||||||
|
//已登录
|
||||||
//先移除之前的用户id,一个用户只能一个
|
if (CurrentUser.Id is not null)
|
||||||
|
{ //先移除之前的用户id,一个用户只能一个
|
||||||
clientUsers.RemoveAll(u => u.UserId == CurrentUser.Id);
|
clientUsers.RemoveAll(u => u.UserId == CurrentUser.Id);
|
||||||
clientUsers.Add(users);
|
|
||||||
_logger.LogInformation($"{DateTime.Now}:{name},{Context.ConnectionId}连接服务端success,当前已连接{clientUsers.Count}个");
|
_logger.LogInformation($"{DateTime.Now}:{name},{Context.ConnectionId}连接服务端success,当前已连接{clientUsers.Count}个");
|
||||||
|
|
||||||
//当有人加入,向全部客户端发送当前总数
|
|
||||||
Clients.All.SendAsync("onlineNum", clientUsers.Count);
|
|
||||||
}
|
}
|
||||||
|
//全部移除之后,再进行添加
|
||||||
|
clientUsers.RemoveAll(u => u.ConnnectionId == Context.ConnectionId);
|
||||||
|
|
||||||
|
clientUsers.Add(user);
|
||||||
|
//当有人加入,向全部客户端发送当前总数
|
||||||
|
Clients.All.SendAsync("onlineNum", clientUsers.Count);
|
||||||
}
|
}
|
||||||
return base.OnConnectedAsync();
|
return base.OnConnectedAsync();
|
||||||
}
|
}
|
||||||
@@ -73,23 +73,18 @@ namespace Yi.Framework.Rbac.Application.SignalRHubs
|
|||||||
{
|
{
|
||||||
lock (objLock)
|
lock (objLock)
|
||||||
{
|
{
|
||||||
var user = clientUsers.Where(p => p.ConnnectionId == Context.ConnectionId).FirstOrDefault();
|
//已登录
|
||||||
//判断用户是否存在,否则添加集合
|
if (CurrentUser.Id is not null)
|
||||||
if (user != null)
|
|
||||||
{
|
{
|
||||||
clientUsers.RemoveAll(u => u.UserId == CurrentUser.Id || u.ConnnectionId == u.ConnnectionId);
|
clientUsers.RemoveAll(u => u.UserId == CurrentUser.Id);
|
||||||
Clients.All.SendAsync("onlineNum", clientUsers.Count);
|
_logger.LogInformation($"用户{CurrentUser?.UserName}离开了,当前已连接{clientUsers.Count}个");
|
||||||
_logger.LogInformation($"用户{user?.UserName}离开了,当前已连接{clientUsers.Count}个");
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
clientUsers.RemoveAll(u => u.ConnnectionId == Context.ConnectionId);
|
||||||
|
Clients.All.SendAsync("onlineNum", clientUsers.Count);
|
||||||
}
|
}
|
||||||
return base.OnDisconnectedAsync(exception);
|
return base.OnDisconnectedAsync(exception);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task SendAllTest(string test)
|
|
||||||
{
|
|
||||||
await Clients.All.SendAsync("ReceiveAllInfo", test);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -59,7 +59,6 @@ namespace Yi.Abp.Web
|
|||||||
var configuration = context.Services.GetConfiguration();
|
var configuration = context.Services.GetConfiguration();
|
||||||
var host = context.Services.GetHostingEnvironment();
|
var host = context.Services.GetHostingEnvironment();
|
||||||
var service = context.Services;
|
var service = context.Services;
|
||||||
|
|
||||||
//请求日志
|
//请求日志
|
||||||
Configure<AbpAuditingOptions>(optios =>
|
Configure<AbpAuditingOptions>(optios =>
|
||||||
{
|
{
|
||||||
@@ -261,8 +260,12 @@ namespace Yi.Abp.Web
|
|||||||
//跨域
|
//跨域
|
||||||
app.UseCors(DefaultCorsPolicyName);
|
app.UseCors(DefaultCorsPolicyName);
|
||||||
|
|
||||||
//速率限制
|
if (!env.IsDevelopment())
|
||||||
app.UseRateLimiter();
|
{
|
||||||
|
//速率限制
|
||||||
|
app.UseRateLimiter();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
//无感token,先刷新再鉴权
|
//无感token,先刷新再鉴权
|
||||||
app.UseRefreshToken();
|
app.UseRefreshToken();
|
||||||
|
|||||||
@@ -6,12 +6,12 @@
|
|||||||
</el-config-provider>
|
</el-config-provider>
|
||||||
</template>
|
</template>
|
||||||
<script setup>
|
<script setup>
|
||||||
import signalR from "@/utils/signalR";
|
import mainHub from "@/hubs/mainHub.js";
|
||||||
import noticeSignalR from "@/utils/noticeSignalR";
|
import noticeSignalR from "@/hubs/noticeHub.js";
|
||||||
import useConfigStore from "@/stores/config";
|
import useConfigStore from "@/stores/config";
|
||||||
import { ElConfigProvider } from "element-plus";
|
import { ElConfigProvider } from "element-plus";
|
||||||
import useUserStore from "@/stores/user.js";
|
import useUserStore from "@/stores/user.js";
|
||||||
import { onMounted,watch,computed } from "vue";
|
import { onMounted, watch, computed } from "vue";
|
||||||
const userStore = useUserStore();
|
const userStore = useUserStore();
|
||||||
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
|
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
|
||||||
const locale = zhCn;
|
const locale = zhCn;
|
||||||
@@ -26,21 +26,18 @@ if (loading !== null) {
|
|||||||
//加载全局信息
|
//加载全局信息
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
await configStore.getConfig();
|
await configStore.getConfig();
|
||||||
noticeSignalR.close();
|
noticeSignalR();
|
||||||
noticeSignalR.init(`notice`);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
watch(
|
watch(
|
||||||
() => token,
|
() => token,
|
||||||
(val,oldValue) => {
|
(val, oldValue) => {
|
||||||
//console.log("token发生改变");
|
//console.log("token发生改变");
|
||||||
if (val) {
|
if (val) {
|
||||||
signalR.close();
|
mainHub();
|
||||||
signalR.init(`main`);
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{immediate:true,deep:true}
|
{ immediate: true, deep: true }
|
||||||
);
|
);
|
||||||
</script>
|
</script>
|
||||||
<style scoped></style>
|
<style scoped></style>
|
||||||
|
|||||||
22
Yi.Bbs.Vue3/src/hubs/mainHub.js
Normal file
22
Yi.Bbs.Vue3/src/hubs/mainHub.js
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import signalR from "@/utils/signalR";
|
||||||
|
import useSocketStore from "@/stores/socket.js";
|
||||||
|
const receiveMsg=(connection)=> {
|
||||||
|
connection.on("onlineNum", (data) => {
|
||||||
|
const socketStore = useSocketStore();
|
||||||
|
socketStore.setOnlineNum(data);
|
||||||
|
});
|
||||||
|
connection.on("forceOut", (msg) => {
|
||||||
|
useUserStore()
|
||||||
|
.logOut()
|
||||||
|
.then(() => {
|
||||||
|
alert(msg);
|
||||||
|
location.href = "/index";
|
||||||
|
});
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ()=>{
|
||||||
|
signalR.start(`main`,receiveMsg);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
28
Yi.Bbs.Vue3/src/hubs/noticeHub.js
Normal file
28
Yi.Bbs.Vue3/src/hubs/noticeHub.js
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import signalR from "@/utils/signalR";
|
||||||
|
const receiveMsg=(connection)=> {
|
||||||
|
connection.on("receiveNotice", (type, title, content) => {
|
||||||
|
switch (type) {
|
||||||
|
case "MerryGoRound":
|
||||||
|
ElNotification({
|
||||||
|
title: title,
|
||||||
|
dangerouslyUseHTMLString: true,
|
||||||
|
message: content,
|
||||||
|
})
|
||||||
|
break;
|
||||||
|
case "Popup":
|
||||||
|
ElNotification({
|
||||||
|
title: title,
|
||||||
|
dangerouslyUseHTMLString: true,
|
||||||
|
message: content,
|
||||||
|
})
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
export default ()=>{
|
||||||
|
signalR.start(`notice`,receiveMsg);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -86,7 +86,6 @@ import useUserStore from "@/stores/user.js";
|
|||||||
import useConfigStore from "@/stores/config";
|
import useConfigStore from "@/stores/config";
|
||||||
import useAuths from "@/hooks/useAuths";
|
import useAuths from "@/hooks/useAuths";
|
||||||
import { Session } from "@/utils/storage";
|
import { Session } from "@/utils/storage";
|
||||||
import signalR from "@/utils/signalR";
|
|
||||||
|
|
||||||
const { isLogin, clearStorage } = useAuths();
|
const { isLogin, clearStorage } = useAuths();
|
||||||
const configStore = useConfigStore();
|
const configStore = useConfigStore();
|
||||||
@@ -106,7 +105,6 @@ const logout = async () => {
|
|||||||
}).then(async () => {
|
}).then(async () => {
|
||||||
//异步
|
//异步
|
||||||
await userStore.logOut();
|
await userStore.logOut();
|
||||||
await signalR.close();
|
|
||||||
//删除成功后,跳转到主页
|
//删除成功后,跳转到主页
|
||||||
router.push("/login");
|
router.push("/login");
|
||||||
ElMessage({
|
ElMessage({
|
||||||
|
|||||||
@@ -1,107 +0,0 @@
|
|||||||
// 官方文档:https://docs.microsoft.com/zh-cn/aspnet/core/signalr/javascript-client?view=aspnetcore-6.0&viewFallbackFrom=aspnetcore-2.2&tabs=visual-studio
|
|
||||||
import * as signalR from "@microsoft/signalr";
|
|
||||||
|
|
||||||
export default {
|
|
||||||
// signalR对象
|
|
||||||
SR: {},
|
|
||||||
// 失败连接重试次数
|
|
||||||
failNum: 4,
|
|
||||||
async init(url) {
|
|
||||||
const connection = new signalR.HubConnectionBuilder()
|
|
||||||
.withUrl(`${import.meta.env.VITE_APP_BASE_WS}/` + url)
|
|
||||||
.withAutomaticReconnect() //自动重新连接
|
|
||||||
.configureLogging(signalR.LogLevel.Information)
|
|
||||||
.build();
|
|
||||||
|
|
||||||
|
|
||||||
this.SR = connection;
|
|
||||||
// 断线重连
|
|
||||||
connection.onclose(async () => {
|
|
||||||
console.log("断开连接了");
|
|
||||||
console.assert(
|
|
||||||
connection.state === signalR.HubConnectionState.Disconnected
|
|
||||||
);
|
|
||||||
// 建议用户重新刷新浏览器
|
|
||||||
});
|
|
||||||
|
|
||||||
connection.onreconnected(() => {
|
|
||||||
console.log("断线重新连接成功");
|
|
||||||
});
|
|
||||||
this.receiveMsg(connection);
|
|
||||||
// 启动
|
|
||||||
await this.start();
|
|
||||||
},
|
|
||||||
/**
|
|
||||||
* 调用 this.signalR.start().then(async () => { await this.SR.invoke("method")})
|
|
||||||
* @returns
|
|
||||||
*/
|
|
||||||
async close() {
|
|
||||||
try {
|
|
||||||
var that = this;
|
|
||||||
await this.SR.stop();
|
|
||||||
this.SR = {};
|
|
||||||
} catch { }
|
|
||||||
},
|
|
||||||
|
|
||||||
async start() {
|
|
||||||
var that = this;
|
|
||||||
|
|
||||||
try {
|
|
||||||
//使用async和await 或 promise的then 和catch 处理来自服务端的异常
|
|
||||||
await this.SR.start();
|
|
||||||
//console.assert(this.SR.state === signalR.HubConnectionState.Connected);
|
|
||||||
//console.log('signalR 连接成功了', this.SR.state);
|
|
||||||
return true;
|
|
||||||
} catch (error) {
|
|
||||||
that.failNum--;
|
|
||||||
//console.log(`失败重试剩余次数${that.failNum}`, error)
|
|
||||||
if (that.failNum > 0) {
|
|
||||||
setTimeout(async () => {
|
|
||||||
await this.SR.start();
|
|
||||||
}, 5000);
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
// 接收消息处理
|
|
||||||
receiveMsg(connection) {
|
|
||||||
connection.on("receiveNotice", (type, title, content) => {
|
|
||||||
|
|
||||||
switch (type) {
|
|
||||||
case "MerryGoRound":
|
|
||||||
ElNotification({
|
|
||||||
title: title,
|
|
||||||
dangerouslyUseHTMLString: true,
|
|
||||||
message: content,
|
|
||||||
})
|
|
||||||
break;
|
|
||||||
case "Popup":
|
|
||||||
ElNotification({
|
|
||||||
title: title,
|
|
||||||
dangerouslyUseHTMLString: true,
|
|
||||||
message: content,
|
|
||||||
})
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// connection.on("onlineNum", (data) => {
|
|
||||||
// store.dispatch("socket/changeOnlineNum", data);
|
|
||||||
// });
|
|
||||||
// // 接收欢迎语
|
|
||||||
// connection.on("welcome", (data) => {
|
|
||||||
// console.log('welcome', data)
|
|
||||||
// Notification.info(data)
|
|
||||||
// });
|
|
||||||
// // 接收后台手动推送消息
|
|
||||||
// connection.on("receiveNotice", (title, data) => {
|
|
||||||
// Notification({
|
|
||||||
// type: 'info',
|
|
||||||
// title: title,
|
|
||||||
// message: data,
|
|
||||||
// dangerouslyUseHTMLString: true,
|
|
||||||
// duration: 0
|
|
||||||
// })
|
|
||||||
// })
|
|
||||||
},
|
|
||||||
};
|
|
||||||
@@ -1,16 +1,11 @@
|
|||||||
// 官方文档:https://docs.microsoft.com/zh-cn/aspnet/core/signalr/javascript-client?view=aspnetcore-6.0&viewFallbackFrom=aspnetcore-2.2&tabs=visual-studio
|
// 官方文档:https://docs.microsoft.com/zh-cn/aspnet/core/signalr/javascript-client?view=aspnetcore-6.0&viewFallbackFrom=aspnetcore-2.2&tabs=visual-studio
|
||||||
import * as signalR from "@microsoft/signalr";
|
import * as signalR from "@microsoft/signalr";
|
||||||
import useSocketStore from "@/stores/socket";
|
|
||||||
import useAuths from "@/hooks/useAuths";
|
import useAuths from "@/hooks/useAuths";
|
||||||
import useUserStore from "@/stores/user";
|
|
||||||
|
|
||||||
const { getToken } = useAuths();
|
const { getToken } = useAuths();
|
||||||
export default {
|
export default {
|
||||||
// signalR对象
|
|
||||||
SR: {},
|
SR: {},
|
||||||
// 失败连接重试次数
|
start(url,callFunc) {
|
||||||
failNum: 4,
|
|
||||||
async init(url) {
|
|
||||||
const connection = new signalR.HubConnectionBuilder()
|
const connection = new signalR.HubConnectionBuilder()
|
||||||
.withUrl(`${import.meta.env.VITE_APP_BASE_WS}/` + url, {
|
.withUrl(`${import.meta.env.VITE_APP_BASE_WS}/` + url, {
|
||||||
headers: {
|
headers: {
|
||||||
@@ -22,97 +17,28 @@ export default {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
.withAutomaticReconnect() //自动重新连接
|
.withAutomaticReconnect(new ForeverRetryPolicy()) //自动重新连接
|
||||||
.configureLogging(signalR.LogLevel.Information)
|
.configureLogging(signalR.LogLevel.Error)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
|
|
||||||
this.SR = connection;
|
this.SR = connection;
|
||||||
// 断线重连
|
// 断线重连
|
||||||
connection.onclose(async () => {
|
connection.onclose(() => {
|
||||||
console.log("断开连接了");
|
console.log("hub断开");
|
||||||
console.assert(
|
|
||||||
connection.state === signalR.HubConnectionState.Disconnected
|
|
||||||
);
|
|
||||||
// 建议用户重新刷新浏览器
|
|
||||||
});
|
});
|
||||||
|
|
||||||
connection.onreconnected(() => {
|
connection.onreconnected(() => {
|
||||||
console.log("断线重新连接成功");
|
console.log("hub重新连接成功");
|
||||||
});
|
});
|
||||||
this.receiveMsg(connection);
|
callFunc(connection);
|
||||||
// 启动
|
// 启动
|
||||||
await this.start();
|
|
||||||
},
|
this.SR.start();
|
||||||
/**
|
|
||||||
* 调用 this.signalR.start().then(async () => { await this.SR.invoke("method")})
|
|
||||||
* @returns
|
|
||||||
*/
|
|
||||||
async close() {
|
|
||||||
try {
|
|
||||||
var that = this;
|
|
||||||
await this.SR.stop();
|
|
||||||
this.SR={};
|
|
||||||
} catch {}
|
|
||||||
},
|
},
|
||||||
|
|
||||||
async start() {
|
|
||||||
var that = this;
|
|
||||||
|
|
||||||
try {
|
|
||||||
//使用async和await 或 promise的then 和catch 处理来自服务端的异常
|
|
||||||
await this.SR.start();
|
|
||||||
//console.assert(this.SR.state === signalR.HubConnectionState.Connected);
|
|
||||||
//console.log('signalR 连接成功了', this.SR.state);
|
|
||||||
return true;
|
|
||||||
} catch (error) {
|
|
||||||
that.failNum--;
|
|
||||||
//console.log(`失败重试剩余次数${that.failNum}`, error)
|
|
||||||
if (that.failNum > 0) {
|
|
||||||
setTimeout(async () => {
|
|
||||||
await this.SR.start();
|
|
||||||
}, 5000);
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
// 接收消息处理
|
|
||||||
receiveMsg(connection) {
|
|
||||||
connection.on("onlineNum", (data) => {
|
|
||||||
const socketStore = useSocketStore();
|
|
||||||
socketStore.setOnlineNum(data);
|
|
||||||
});
|
|
||||||
connection.on("forceOut", (msg) => {
|
|
||||||
useUserStore()
|
|
||||||
.logOut()
|
|
||||||
.then(() => {
|
|
||||||
alert(msg);
|
|
||||||
location.href = "/index";
|
|
||||||
});
|
|
||||||
});
|
|
||||||
// connection.on("onlineNum", (data) => {
|
|
||||||
// store.dispatch("socket/changeOnlineNum", data);
|
|
||||||
// });
|
|
||||||
// // 接收欢迎语
|
|
||||||
// connection.on("welcome", (data) => {
|
|
||||||
// console.log('welcome', data)
|
|
||||||
// Notification.info(data)
|
|
||||||
// });
|
|
||||||
// // 接收后台手动推送消息
|
|
||||||
// connection.on("receiveNotice", (title, data) => {
|
|
||||||
// Notification({
|
|
||||||
// type: 'info',
|
|
||||||
// title: title,
|
|
||||||
// message: data,
|
|
||||||
// dangerouslyUseHTMLString: true,
|
|
||||||
// duration: 0
|
|
||||||
// })
|
|
||||||
// })
|
|
||||||
// // 接收系统通知/公告
|
|
||||||
// connection.on("moreNotice", (data) => {
|
|
||||||
// if (data.code == 200) {
|
|
||||||
// store.dispatch("socket/getNoticeList", data.data);
|
|
||||||
// }
|
|
||||||
// })
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
class ForeverRetryPolicy {
|
||||||
|
nextRetryDelayInMilliseconds(retryContext) {
|
||||||
|
return 1000*3;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user