实时在线用户功能

This commit is contained in:
橙子
2022-10-03 17:04:59 +08:00
parent e963a4051f
commit 3943536485
25 changed files with 528 additions and 33 deletions

View File

@@ -410,6 +410,17 @@
测试控制器
</summary>
</member>
<member name="M:Yi.Framework.ApiMicroservice.Controllers.TestController.#ctor(Microsoft.AspNetCore.SignalR.IHubContext{Yi.Framework.WebCore.SignalRHub.MainHub},Microsoft.Extensions.Logging.ILogger{Yi.Framework.Model.Models.UserEntity},Yi.Framework.Interface.IRoleService,Yi.Framework.Interface.IUserService,Microsoft.Extensions.Localization.IStringLocalizer{Yi.Framework.Language.LocalLanguage},Yi.Framework.Core.QuartzInvoker)">
<summary>
依赖注入
</summary>
<param name="hub"></param>
<param name="logger"></param>
<param name="iRoleService"></param>
<param name="iUserService"></param>
<param name="local"></param>
<param name="quartzInvoker"></param>
</member>
<member name="M:Yi.Framework.ApiMicroservice.Controllers.TestController.Swagger">
<summary>
swagger跳转
@@ -501,6 +512,13 @@
<param name="par"></param>
<returns></returns>
</member>
<member name="M:Yi.Framework.ApiMicroservice.Controllers.TestController.SignalrTest(System.Int32)">
<summary>
Signalr实时推送测试
</summary>
<param name="msg"></param>
<returns></returns>
</member>
<member name="T:Yi.Framework.ApiMicroservice.Controllers.UserController">
<summary>
用户管理

View File

@@ -0,0 +1,211 @@
using Hei.Captcha;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Yi.Framework.Common.Const;
using Yi.Framework.Common.Enum;
using Yi.Framework.Common.Helper;
using Yi.Framework.Common.Models;
using Yi.Framework.Core;
using Yi.Framework.DTOModel;
using Yi.Framework.Interface;
using Yi.Framework.Model.Models;
using Yi.Framework.Repository;
using Yi.Framework.WebCore;
using Yi.Framework.WebCore.AttributeExtend;
using Yi.Framework.WebCore.AuthorizationPolicy;
namespace Yi.Framework.ApiMicroservice.Controllers
{
/// <summary>
/// 账户管理
/// </summary>
[ApiController]
[Authorize]
[Route("api/[controller]/[action]")]
public class AccountController : ControllerBase
{
private IUserService _iUserService;
private JwtInvoker _jwtInvoker;
private ILogger _logger;
private SecurityCodeHelper _securityCode;
private IRepository<UserEntity> _repository;
public AccountController(ILogger<UserEntity> logger, IUserService iUserService, JwtInvoker jwtInvoker, SecurityCodeHelper securityCode)
{
_iUserService = iUserService;
_jwtInvoker = jwtInvoker;
_logger = logger;
_securityCode = securityCode;
_repository = iUserService._repository;
}
/// <summary>
/// 重置管理员CC的密码
/// </summary>
/// <returns></returns>
[HttpGet]
[AllowAnonymous]
public async Task<Result> RestCC()
{
var user = await _iUserService._repository.GetFirstAsync(u => u.UserName == "cc");
user.Password = "123456";
user.BuildPassword();
await _iUserService._repository.UpdateIgnoreNullAsync(user);
return Result.Success();
}
/// <summary>
/// 没啥说,登录
/// </summary>
/// <param name="loginDto"></param>
/// <returns></returns>
[AllowAnonymous]
[HttpPost]
public async Task<Result> Login(LoginDto loginDto)
{
//跳过需要redis缓存获取uuid与code的关系进行比较即可
//先效验验证码和UUID
//登录还需要进行登录日志的落库
var loginInfo = HttpContext.GetLoginLogInfo();
loginInfo.LoginUser = loginDto.UserName;
loginInfo.LogMsg = "登录成功!";
var loginLogRepository = _repository.ChangeRepository<Repository<LoginLogEntity>>();
UserEntity user = new();
if (await _iUserService.Login(loginDto.UserName, loginDto.Password, o => user = o))
{
var userRoleMenu = await _iUserService.GetUserAllInfo(user.Id);
await loginLogRepository.InsertReturnSnowflakeIdAsync(loginInfo);
return Result.Success(loginInfo.LogMsg).SetData(new { token = _jwtInvoker.GetAccessToken(userRoleMenu.User, userRoleMenu.Menus) });
}
loginInfo.LogMsg = "登录失败!用户名或者密码错误!";
await loginLogRepository.InsertReturnSnowflakeIdAsync(loginInfo);
return Result.Error(loginInfo.LogMsg);
}
/// <summary>
/// 没啥说,注册
/// </summary>
/// <param name="registerDto"></param>
/// <returns></returns>
[AllowAnonymous]
[HttpPost]
public async Task<Result> Register(RegisterDto registerDto)
{
UserEntity user = new();
if (await _iUserService.Register(WebCore.Mapper.MapperHelper.Map<UserEntity, RegisterDto>(registerDto), o => user = o))
{
return Result.Success("注册成功!").SetData(user);
}
return Result.SuccessError("注册失败!用户名已存在!");
}
/// <summary>
/// 没啥说,登出
/// </summary>
/// <returns></returns>
[HttpPost]
[AllowAnonymous]
public Result Logout()
{
return Result.Success("安全登出成功!");
}
/// <summary>
/// 通过已登录的用户获取用户信息
/// </summary>
/// <returns></returns>
[HttpGet]
//[Authorize]
public async Task<Result> GetUserAllInfo()
{
//通过鉴权jwt获取到用户的id
var userId = HttpContext.GetUserIdInfo();
var data = await _iUserService.GetUserAllInfo(userId);
//系统用户数据被重置,老前端访问重新授权
if (data is null)
{
return Result.UnAuthorize();
}
data.Menus.Clear();
return Result.Success().SetData(data);
}
/// <summary>
/// 获取当前登录用户的前端路由
/// </summary>
/// <returns></returns>
[HttpGet]
public async Task<Result> GetRouterInfo()
{
var userId = HttpContext.GetUserIdInfo();
var data = await _iUserService.GetUserAllInfo(userId);
var menus = data.Menus.ToList();
//为超级管理员直接给全部路由
if (SystemConst.Admin.Equals(data.User.UserName))
{
menus = await _iUserService._repository.ChangeRepository<Repository<MenuEntity>>().GetListAsync();
}
//将后端菜单转换成前端路由,组件级别需要过滤
List<VueRouterModel> routers = MenuEntity.RouterBuild(menus);
return Result.Success().SetData(routers);
}
/// <summary>
/// 更新已登录用户的用户信息
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
[HttpPut]
public async Task<Result> UpdateUserByHttp(UserEntity user)
{
//当然,密码是不能给他修改的
user.Password = null;
user.Salt = null;
//修改需要赋值上主键哦
user.Id = HttpContext.GetUserIdInfo();
return Result.Success().SetStatus(await _iUserService._repository.UpdateIgnoreNullAsync(user));
}
/// <summary>
/// 自己更新密码
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
[HttpPut]
public async Task<Result> UpdatePassword(UpdatePasswordDto dto)
{
long userId = HttpContext.GetUserIdInfo();
if (await _iUserService.UpdatePassword(dto, userId))
{
return Result.Success();
}
return Result.Error("更新失败!");
}
/// <summary>
/// 验证码
/// </summary>
/// <returns></returns>
[AllowAnonymous]
[HttpGet]
public Result CaptchaImage()
{
var uuid = Guid.NewGuid();
var code = _securityCode.GetRandomEnDigitalText(4);
//将uuid与codeRedis缓存中心化保存起来登录根据uuid比对即可
var imgbyte = _securityCode.GetEnDigitalCodeByte(code);
return Result.Success().SetData(new { uuid = uuid, img = imgbyte });
}
}
}

View File

@@ -1,5 +1,6 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using System;
@@ -17,6 +18,7 @@ using Yi.Framework.WebCore;
using Yi.Framework.WebCore.AttributeExtend;
using Yi.Framework.WebCore.AuthorizationPolicy;
using Yi.Framework.WebCore.DbExtend;
using Yi.Framework.WebCore.SignalRHub;
namespace Yi.Framework.ApiMicroservice.Controllers
{
@@ -31,13 +33,23 @@ namespace Yi.Framework.ApiMicroservice.Controllers
private IUserService _iUserService;
private IRoleService _iRoleService;
private QuartzInvoker _quartzInvoker;
private IHubContext<MainHub> _hub;
//你可以依赖注入服务层各各接口,也可以注入其他仓储层,怎么爽怎么来!
public TestController(ILogger<UserEntity> logger, IRoleService iRoleService, IUserService iUserService, IStringLocalizer<LocalLanguage> local, QuartzInvoker quartzInvoker)
/// <summary>
/// 依赖注入
/// </summary>
/// <param name="hub"></param>
/// <param name="logger"></param>
/// <param name="iRoleService"></param>
/// <param name="iUserService"></param>
/// <param name="local"></param>
/// <param name="quartzInvoker"></param>
public TestController(IHubContext<MainHub> hub , ILogger<UserEntity> logger, IRoleService iRoleService, IUserService iUserService, IStringLocalizer<LocalLanguage> local, QuartzInvoker quartzInvoker)
{
_local = local;
_iUserService = iUserService;
_iRoleService = iRoleService;
_quartzInvoker = quartzInvoker;
_hub = hub;
}
/// <summary>
@@ -269,5 +281,17 @@ namespace Yi.Framework.ApiMicroservice.Controllers
{
return Result.Success().SetData(par);
}
/// <summary>
/// Signalr实时推送测试
/// </summary>
/// <param name="msg"></param>
/// <returns></returns>
[HttpGet]
public async Task<Result> SignalrTest(int msg)
{
await _hub.Clients.All.SendAsync("onlineNum", msg);
return Result.Success("向所有连接客户端发送一个消息");
}
}
}

View File

@@ -57,6 +57,7 @@ namespace Yi.Framework.ApiMicroservice.Controllers
/// <returns></returns>
[HttpPut]
[Permission("system:user:edit")]
[Log("用户模块", OperEnum.Update)]
public async Task<Result> UpdateStatus(long userId, bool isDel)
{
return Result.Success().SetData(await _repository.UpdateIgnoreNullAsync(new UserEntity() { Id = userId, IsDeleted = isDel }));
@@ -69,6 +70,7 @@ namespace Yi.Framework.ApiMicroservice.Controllers
/// <returns></returns>
[HttpPut]
[Permission("system:user:edit")]
[Log("用户模块", OperEnum.Update)]
public async Task<Result> GiveUserSetRole(GiveUserSetRoleDto giveUserSetRoleDto)
{
return Result.Success().SetStatus(await _iUserService.GiveUserSetRole(giveUserSetRoleDto.UserIds, giveUserSetRoleDto.RoleIds));
@@ -95,6 +97,7 @@ namespace Yi.Framework.ApiMicroservice.Controllers
/// <returns></returns>
[HttpPut]
[Permission("system:user:edit")]
[Log("用户模块", OperEnum.Update)]
public async Task<Result> Update(UserInfoDto userDto)
{
if (await _repository.IsAnyAsync(u => userDto.User.UserName.Equals(u.UserName) && !userDto.User.Id.Equals(u.Id)))
@@ -112,6 +115,7 @@ namespace Yi.Framework.ApiMicroservice.Controllers
/// <returns></returns>
[HttpPut]
[Permission("system:user:edit")]
[Log("用户模块", OperEnum.Update)]
public async Task<Result> UpdateProfile(UserInfoDto userDto)
{
return Result.Success().SetStatus(await _iUserService.UpdateProfile(userDto));
@@ -123,9 +127,14 @@ namespace Yi.Framework.ApiMicroservice.Controllers
/// <param name="userDto"></param>
/// <returns></returns>
[HttpPost]
[Permission("system:user:add2")]
[Permission("system:user:add")]
[Log("用户模块", OperEnum.Insert)]
public async Task<Result> Add(UserInfoDto userDto)
{
if (string.IsNullOrEmpty(userDto.User.Password))
{
return Result.Error("密码为空,添加失败!");
}
if (await _repository.IsAnyAsync(u => userDto.User.UserName.Equals(u.UserName)))
{
return Result.Error("用户已经存在,添加失败!");
@@ -141,6 +150,7 @@ namespace Yi.Framework.ApiMicroservice.Controllers
/// <returns></returns>
[HttpPut]
[Permission("system:user:edit")]
[Log("用户模块", OperEnum.Update)]
public async Task<Result> RestPassword(UserEntity user)
{
return Result.Success().SetStatus(await _iUserService.RestPassword(user.Id, user.Password));
@@ -151,6 +161,7 @@ namespace Yi.Framework.ApiMicroservice.Controllers
return base.GetList();
}
[Permission("system:user:remove")]
[Log("用户模块", OperEnum.Delete)]
public override Task<Result> DelList(List<long> ids)
{
return base.DelList(ids);

View File

@@ -14,6 +14,7 @@ using Hei.Captcha;
using Yi.Framework.WebCore;
using Microsoft.Extensions.DependencyInjection;
using Yi.Framework.WebCore.DbExtend;
using IPTools.Core;
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddCommandLine(args);
@@ -205,13 +206,13 @@ app.UseDbSeedInitService();
//redis<69><73><EFBFBD><EFBFBD>ע<EFBFBD><D7A2>
#endregion
app.UseRedisSeedInitService();
#region
//SignalR<6C><52><EFBFBD><EFBFBD>
#endregion
app.MapHub<MainHub>("/hub/main");
app.UseEndpoints(endpoints =>
{
#region
//SignalR<6C><52><EFBFBD><EFBFBD>
#endregion
endpoints.MapHub<MainHub>("/api/hub/main");
endpoints.MapControllers();
});

View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Yi.Framework.Common.Enum
{
public enum HubTypeEnum
{
onlineNum,
}
}

View File

@@ -7,7 +7,7 @@
<ItemGroup>
<PackageReference Include="EPPlus" Version="5.8.4" />
<PackageReference Include="Hei.Captcha" Version="0.3.0" />
<PackageReference Include="IPTools.Core" Version="1.6.0" />
<PackageReference Include="IPTools.China" Version="1.6.0" />
<PackageReference Include="Microsoft.Extensions.Localization.Abstractions" Version="6.0.3" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="SharpZipLib" Version="1.3.3" />

View File

@@ -19,7 +19,7 @@ namespace Yi.Framework.Service
.WhereIF(!string.IsNullOrEmpty(loginLog.LoginUser), u => u.LoginUser.Contains(loginLog.LoginUser))
.WhereIF(loginLog.IsDeleted.IsNotNull(), u => u.IsDeleted == loginLog.IsDeleted)
.WhereIF(page.StartTime.IsNotNull() && page.EndTime.IsNotNull(), u => u.CreateTime >= page.StartTime && u.CreateTime <= page.EndTime)
.OrderBy(u => u.OrderNum, OrderByType.Desc)
.OrderBy(u => u.CreateTime, OrderByType.Desc)
.ToPageListAsync(page.PageNum, page.PageSize, total);
return new PageModel<List<LoginLogEntity>>(data, total);
}

View File

@@ -20,7 +20,7 @@ namespace Yi.Framework.Service
.WhereIF(operationLog.OperType is not null, u => u.OperType==operationLog.OperType.GetHashCode())
.WhereIF(operationLog.IsDeleted.IsNotNull(), u => u.IsDeleted == operationLog.IsDeleted)
.WhereIF(page.StartTime.IsNotNull() && page.EndTime.IsNotNull(), u => u.CreateTime >= page.StartTime && u.CreateTime <= page.EndTime)
.OrderBy(u => u.OrderNum, OrderByType.Desc)
.OrderBy(u => u.CreateTime, OrderByType.Desc)
.ToPageListAsync(page.PageNum, page.PageSize, total);
return new PageModel<List<OperationLogEntity>>(data, total);

View File

@@ -51,8 +51,8 @@ namespace Yi.Framework.WebCore.AttributeExtend
//根据ip获取地址
//var ipTool = IpTool.Search(ip);
//string location = ipTool.Province + " " + ipTool.City;
var ipTool = IpTool.Search(ip);
string location = ipTool.Province + " " + ipTool.City;
//日志服务插入一条操作记录即可
@@ -66,6 +66,7 @@ namespace Yi.Framework.WebCore.AttributeExtend
logEntity.Method = context.HttpContext.Request.Path.Value;
logEntity.IsDeleted = false;
logEntity.OperUser= context.HttpContext.GetUserNameInfo();
logEntity.OperLocation = location;
if (logAttribute.IsSaveResponseData)
{
if (context.Result is ContentResult result && result.ContentType == "application/json")

View File

@@ -12,6 +12,7 @@ using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Text.RegularExpressions;
using UAParser;
using IPTools.Core;
namespace Yi.Framework.WebCore
{
@@ -86,7 +87,7 @@ namespace Yi.Framework.WebCore
try
{
claimlist = httpContext.User.Claims;
resId = Convert.ToInt64(claimlist.FirstOrDefault(u => u.Type == JwtRegisteredClaimNames.Sid).Value);
resId = Convert.ToInt64(claimlist.FirstOrDefault(u => u.Type == JwtRegisteredClaimNames.Sid)?.Value);
}
catch
{
@@ -224,8 +225,7 @@ namespace Yi.Framework.WebCore
public static LoginLogEntity GetLoginLogInfo(this HttpContext context)
{
var ipAddr = context.GetClientIp();
//var ip_info = IpTool.Search(ipAddr);
//var location = "广州" + "-" + "深圳";
var location = IpTool.Search(ipAddr);
ClientInfo clientInfo = context.GetClientInfo();
LoginLogEntity entity = new()
{
@@ -234,7 +234,7 @@ namespace Yi.Framework.WebCore
LoginIp = ipAddr,
//登录是没有token的所有是获取不到用户名需要在控制器赋值
//LoginUser = context.GetUserNameInfo(),
LoginLocation = "广州" + "-" + "深圳",
LoginLocation = location.Province + "-" + location.City,
IsDeleted = false
};

View File

@@ -95,16 +95,21 @@ namespace Yi.Framework.WebCore.MiddlewareExtend
};
db.Aop.OnLogExecuting = (s, p) =>
{
var _logger = ServiceLocator.Instance.GetService<ILogger<SqlSugarClient>>();
StringBuilder sb = new StringBuilder();
sb.Append("执行SQL:" + s.ToString());
foreach (var i in p)
//暂时先关闭sql打印
if (false)
{
sb.Append($"\r\n参数:{i.ParameterName},参数值:{i.Value}");
}
var _logger = ServiceLocator.Instance.GetService<ILogger<SqlSugarClient>>();
_logger.LogInformation(sb.ToString());
StringBuilder sb = new StringBuilder();
sb.Append("执行SQL:" + s.ToString());
foreach (var i in p)
{
sb.Append($"\r\n参数:{i.ParameterName},参数值:{i.Value}");
}
_logger.LogInformation(sb.ToString());
}
};

View File

@@ -1,21 +1,74 @@
using Microsoft.AspNetCore.SignalR;
using IPTools.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yi.Framework.Common.Enum;
namespace Yi.Framework.WebCore.SignalRHub
{
public class MainHub : Hub
{
private HttpContext _httpContext;
private ILogger<MainHub> _logger;
public MainHub(IHttpContextAccessor httpContextAccessor,ILogger<MainHub> logger)
{
_httpContext = httpContextAccessor.HttpContext;
_logger = logger;
}
private static readonly List<OnlineUser> clientUsers = new();
/// <summary>
/// 成功连接
/// </summary>
/// <returns></returns>
public override Task OnConnectedAsync()
{
var name = _httpContext.GetUserNameInfo();
var ip = _httpContext.GetClientIp();
var ip_info = IpTool.Search(ip);
var loginUser = _httpContext.GetUserEntityInfo(out _);
var user = clientUsers.Any(u => u.ConnnectionId == Context.ConnectionId);
//判断用户是否存在,否则添加集合
if (!user && Context.User.Identity.IsAuthenticated)
{
OnlineUser users = new(Context.ConnectionId, name, loginUser.Id, ip)
{
Location = ip_info.City
};
clientUsers.Add(users);
_logger.LogInformation($"{DateTime.Now}{name},{Context.ConnectionId}连接服务端success当前已连接{clientUsers.Count}个");
//Clients.All.SendAsync(HubsConstant.MoreNotice, SendNotice());
}
//当有人加入,向全部客户端发送当前总数
Clients.All.SendAsync(HubTypeEnum.onlineNum.ToString(), clientUsers.Count);
//Clients.All.SendAsync(HubsConstant.OnlineUser, clientUsers);
return base.OnConnectedAsync();
}
/// <summary>
/// 断开连接
/// </summary>
/// <param name="exception"></param>
/// <returns></returns>
public override Task OnDisconnectedAsync(Exception exception)
{
var user = clientUsers.Where(p => p.ConnnectionId == Context.ConnectionId).FirstOrDefault();
//判断用户是否存在,否则添加集合
if (user != null)
{
clientUsers.Remove(user);
Clients.All.SendAsync(HubTypeEnum.onlineNum.ToString(), clientUsers.Count);
//Clients.All.SendAsync(HubsConstant.OnlineUser, clientUsers);
_logger.LogInformation($"用户{user?.Name}离开了,当前已连接{clientUsers.Count}个");
}
return base.OnDisconnectedAsync(exception);
}

View File

@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Yi.Framework.WebCore.SignalRHub
{
public class OnlineUser
{
/// <summary>
/// 客户端连接Id
/// </summary>
public string ConnnectionId { get; set; }
/// <summary>
/// 用户id
/// </summary>
public long? Userid { get; set; }
public string Name { get; set; }
public DateTime LoginTime { get; set; }
public string UserIP { get; set; }
public string Location { get; set; }
public OnlineUser(string clientid, string name, long? userid, string userip)
{
ConnnectionId = clientid;
Name = name;
LoginTime = DateTime.Now;
Userid = userid;
UserIP = userip;
}
}
}

View File

@@ -7,4 +7,5 @@ VITE_APP_ENV = 'development'
# 若依管理系统/开发环境
VITE_APP_BASE_API = '/dev-api'
VITE_APP_BASE_URL='http://localhost:19001/api'
VITE_APP_BASE_URL='http://localhost:19001/api'

View File

@@ -8,4 +8,5 @@ VITE_APP_ENV = 'production'
VITE_APP_BASE_API = '/prod-api'
# 是否在打包时开启压缩,支持 gzip 和 brotli
VITE_BUILD_COMPRESS = gzip
VITE_BUILD_COMPRESS = gzip

View File

@@ -8,4 +8,5 @@ VITE_APP_ENV = 'staging'
VITE_APP_BASE_API = '/stage-api'
# 是否在打包时开启压缩,支持 gzip 和 brotli
VITE_BUILD_COMPRESS = gzip
VITE_BUILD_COMPRESS = gzip

View File

@@ -16,6 +16,7 @@
},
"dependencies": {
"@element-plus/icons-vue": "1.1.4",
"@microsoft/signalr": "^6.0.9",
"@vueuse/core": "8.5.0",
"axios": "0.26.1",
"echarts": "5.3.2",
@@ -24,13 +25,13 @@
"fuse.js": "6.5.3",
"js-cookie": "3.0.1",
"jsencrypt": "3.2.1",
"json-bigint": "^1.0.0",
"nprogress": "0.2.0",
"pinia": "2.0.14",
"typeface-roboto": "^1.1.13",
"vue": "3.2.37",
"vue-cropper": "1.0.3",
"vue-router": "4.0.14",
"json-bigint": "^1.0.0",
"typeface-roboto": "^1.1.13"
"vue-router": "4.0.14"
},
"devDependencies": {
"@vitejs/plugin-vue": "2.3.3",

View File

@@ -12,4 +12,6 @@ onMounted(() => {
handleThemeStyle(useSettingsStore().theme)
})
})
//这里还需要监视token的变化重新进行signalr连接
</script>

View File

@@ -21,6 +21,7 @@ import { download } from '@/utils/ruoyi.js'
import 'virtual:svg-icons-register'
import SvgIcon from '@/components/SvgIcon'
import elementIcons from '@/components/SvgIcon/svgicon'
import signalR from '@/utils/signalR'
import './permission' // permission control
@@ -77,5 +78,8 @@ app.use(ElementPlus, {
// 支持 large、default、small
size: Cookies.get('size') || 'default'
})
// app.prototype.signalr = signalR
signalR.init("http://localhost:19001/api/hub/main");
signalR.start();
app.mount('#app')

View File

@@ -15,7 +15,6 @@ const whiteList = ['/login', '/auth-redirect', '/bind', '/register'];
router.beforeEach((to, from, next) => {
NProgress.start()
console.log(router.getRoutes() ,"123")
if (getToken()) {
to.meta.title && useSettingsStore().setTitle(to.meta.title)
/* has token*/

View File

@@ -0,0 +1,20 @@
const socketStore = defineStore(
'socket',
{
state: () => ({
onlineNum: 1
}),
actions: {
// 获取在线总数
getOnlineNum() {
return this.onlineNum;
},
// 设置在线总数
setOnlineNum(value) {
this.onlineNum = value;
}
}
})
export default socketStore

View File

@@ -0,0 +1,90 @@
// 官方文档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 useSocketStore from '@/store/modules/socket'
import { getToken } from '@/utils/auth'
export default {
// signalR对象
SR: {},
// 失败连接重试次数
failNum: 4,
baseUrl: '',
init(url) {
const connection = new signalR.HubConnectionBuilder()
.withUrl(url, { accessTokenFactory: () => getToken() })
.withAutomaticReconnect()//自动重新连接
.configureLogging(signalR.LogLevel.Information)
.build();
this.SR = connection;
// 断线重连
connection.onclose(async () => {
console.log('断开连接了')
console.assert(connection.state === signalR.HubConnectionState.Disconnected);
// 建议用户重新刷新浏览器
await this.start();
})
connection.onreconnected(() => {
console.log('断线重新连接成功')
})
this.receiveMsg(connection);
// 启动
// this.start();
},
/**
* 调用 this.signalR.start().then(async () => { await this.SR.invoke("method")})
* @returns
*/
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("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);
// }
// })
}
}

View File

@@ -40,6 +40,7 @@
<el-row :gutter="20">
<el-col :sm="24" :lg="12" style="padding-left: 20px">
<h2>意框架-若依后台管理框架</h2>
<h3>当前在线人数{{onlineNum}}</h3>
<p>
Ruoyi:一直想做一款后台管理系统看了很多优秀的开源项目但是发现没有合适自己的于是利用空闲休息时间开始自己写一套后台系统如此有了若依管理系统她可以用于所有的Web应用程序如网站管理后台网站会员中心CMSCRMOA等等当然您也可以对她进行深度定制以做出更强系统所有前端后台代码封装过后十分精简易上手出错概率低同时支持移动客户端访问系统会陆续更新一些实用功能
</p>
@@ -854,8 +855,14 @@
</template>
<script setup name="Index">
import useSocketStore from '@/store/modules/socket'
import { ref } from 'vue-demi';
import { storeToRefs } from 'pinia';
const socketStore=useSocketStore();
const {onlineNum}=storeToRefs(socketStore);
const version = ref('3.8.3')
function goTarget(url) {
window.open(url, '__blank')
}