This commit is contained in:
youngq 2024-07-25 17:38:51 +08:00
parent b2e9814a90
commit 184493f71b
8 changed files with 85 additions and 41 deletions

View File

@ -82,7 +82,7 @@ namespace WGShare.API.Controllers
btnAutn.Add(new Claim("uname", user.UserName));
var refreshToken = Guid.NewGuid().ToString();
RedisHelper.Instance.Set(refreshToken, user, TimeSpan.FromDays(30).TotalSeconds.ToInt32());
RedisHelper.Instance.Set($@"refresh:{refreshToken}", user, TimeSpan.FromDays(30).TotalSeconds.ToInt32());
return Ok(new
{
@ -106,7 +106,7 @@ namespace WGShare.API.Controllers
[HttpPost("refresh"), AllowAnonymous]
public async Task<IActionResult> Refresh([FromQuery] string refreshToken)
{
var user = RedisHelper.Instance.Get<User>(refreshToken);
var user = RedisHelper.Instance.Get<User>($@"refresh:{refreshToken}");
if (user == null || string.IsNullOrWhiteSpace(user.Id))
{
throw Oops.Oh("登录已失效,请重新登录");
@ -121,8 +121,8 @@ namespace WGShare.API.Controllers
var refreshTokenNew = Guid.NewGuid().ToString();
RedisHelper.Instance.Del(refreshToken);
RedisHelper.Instance.Set(refreshTokenNew, user, TimeSpan.FromDays(30).TotalSeconds.ToInt32());
RedisHelper.Instance.Del($@"refresh:{refreshToken}");
RedisHelper.Instance.Set($@"refresh:{refreshTokenNew}", user, TimeSpan.FromDays(30).TotalSeconds.ToInt32());
return Ok(new
{

View File

@ -63,12 +63,13 @@ namespace WGShare.API.Controllers.Frontend
if (!result.IsNullOrEmpty())
{
// 从Redis获取缓存在线人数 拼装数据
var userCounts = RedisHelper.Instance.HMGet<int>(RedisKeyConstant.SessionManage.GetChannelUserCountKey(TenantId),
result.Select(x => x.RoomNum).ToArray());
for (int i = 0; i < userCounts.Length; i++)
{
result[i].OnlineUserCount = userCounts[i];
}
result.ForEach(x => x.OnlineUserCount = RedisHelper.Instance.HLen(RedisKeyConstant.SessionManage.GetChannelUserKey(TenantId, x.RoomNum)));
//var userCounts = RedisHelper.Instance.HMGet<int>(RedisKeyConstant.SessionManage.GetChannelUserCountKey(TenantId),
// result.Select(x => x.RoomNum).ToArray());
//for (int i = 0; i < userCounts.Length; i++)
//{
// result[i].OnlineUserCount = userCounts[i];
//}
}
return PagedResult<RoomOutputDTO>.Create(result, total.Value);
@ -103,7 +104,7 @@ namespace WGShare.API.Controllers.Frontend
/// 获取 rtm token
/// </summary>
/// <returns></returns>
[HttpGet("tk/rtm"),Obsolete]
[HttpGet("tk/rtm"), Obsolete]
public async Task<string> GetRTMToken()
{
uint privilegeExpiredTs = (uint)_configuration["tokenExpireTimeInSecond"].ToInt32() + (uint)Utils.getTimestamp();

View File

@ -1,6 +1,8 @@
using Masuit.Tools;
using Masuit.Tools.Maths;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using SqlSugar;
using System.Text;
using WGShare.API.Helpers;
using WGShare.Domain.Constant;
@ -11,16 +13,22 @@ namespace WGShare.API.Hubs
[Authorize]
public class SessionManageHub : Hub<IMessageClient>
{
private readonly ILogger<SessionManageHub> _logger;
public SessionManageHub(ILogger<SessionManageHub> logger)
{
this._logger = logger;
}
public async override Task OnConnectedAsync()
{
var tenant = Context.User?.Claims.FirstOrDefault(x => x.Type == "tenant")?.Value;
var uid = Context.User?.Claims.FirstOrDefault(x => x.Type == "uid")?.Value;
Console.WriteLine($"{DateTime.Now}连接成功 当前租户:" + tenant);
Console.WriteLine($"{DateTime.Now} 连接成功 uid" + uid);
Console.WriteLine($"{DateTime.Now}连接成功 connectId" + Context.ConnectionId);
await Console.Out.WriteLineAsync("连接成功 当前租户:" + tenant);
await Console.Out.WriteLineAsync("连接成功 uid" + uid);
await Console.Out.WriteLineAsync("连接成功 connectId" + Context.ConnectionId);
await ClearUserChannel(uid, tenant);
// 存储在线信息
RedisHelper.Instance.HSet(RedisKeyConstant.SessionManage.GetOnlineUserKey(tenant), uid, Context.ConnectionId);
}
@ -30,32 +38,49 @@ namespace WGShare.API.Hubs
var tenant = Context.User?.Claims.FirstOrDefault(x => x.Type == "tenant")?.Value;
var uid = Context.User?.Claims.FirstOrDefault(x => x.Type == "uid")?.Value;
await Console.Out.WriteLineAsync("断开连接 当前租户:" + tenant);
await Console.Out.WriteLineAsync("断开连接 uid" + uid);
await Console.Out.WriteLineAsync("断开连接 connectId" + Context.ConnectionId);
Console.WriteLine($"{DateTime.Now}断开连接 当前租户:" + tenant);
Console.WriteLine($"{DateTime.Now}断开连接 uid" + uid);
Console.WriteLine($"{DateTime.Now}断开连接 connectId" + Context.ConnectionId);
// 获取用户参加得频道
if (Context.ConnectionId == RedisHelper.Instance.HGet(RedisKeyConstant.SessionManage.GetOnlineUserKey(tenant), uid))
{
Console.WriteLine($"{DateTime.Now}断开连接 True");
// 断开后未重连则清退频道
await ClearUserChannel(uid, tenant);
}
}
private async Task ClearUserChannel(string uid, string tenant)
{
Console.WriteLine($"{DateTime.Now} 执行删除");
var roomNums = RedisHelper.Instance.HKeys(RedisKeyConstant.SessionManage.GetUserJoinChannelKey(uid));
using (var pipe = RedisHelper.Instance.StartPipe())
{
// 移除在线信息
pipe.HDel(RedisKeyConstant.SessionManage.GetOnlineUserKey(tenant), uid);
// 获取用户参加得频道
//var roomNums = pipe.HKeys(RedisKeyConstant.SessionManage.GetUserJoinChannelKey(uid));
if (!roomNums.IsNullOrEmpty())
{
await Console.Out.WriteLineAsync($@"uid:{uid} 退出以下频道:{string.Join(',', roomNums)}");
Console.WriteLine($@"{DateTime.Now}uid:{uid} 退出以下频道:{string.Join(',', roomNums)}");
// 所有房间移除该用户
roomNums.ForEach(roomNum =>
{
pipe.HDel(RedisKeyConstant.SessionManage.GetChannelUserKey(tenant, roomNum), uid);
pipe.HIncrBy(RedisKeyConstant.SessionManage.GetChannelUserCountKey(tenant), roomNum, -1);
//pipe.HIncrBy(RedisKeyConstant.SessionManage.GetChannelUserCountKey(tenant), roomNum, -1);
});
}
// 删除用户在线状态
pipe.HDel(RedisKeyConstant.SessionManage.GetOnlineUserKey(tenant), uid);
// 删除用户已加入频道信息
pipe.Del(RedisKeyConstant.SessionManage.GetUserJoinChannelKey(uid));
pipe.EndPipe();
}
Console.WriteLine($"{DateTime.Now} 执行删除 完成");
}
/// <summary>
@ -71,15 +96,15 @@ namespace WGShare.API.Hubs
var uid = Context.User?.Claims.FirstOrDefault(x => x.Type == "uid")?.Value;
await Console.Out.WriteLineAsync("加入频道 会议号:" + roomNum);
await Console.Out.WriteLineAsync("加入频道 uid" + uid);
await Console.Out.WriteLineAsync("加入频道 tenant" + tenant);
Console.WriteLine($"{DateTime.Now}加入频道 会议号:" + roomNum);
Console.WriteLine($"{DateTime.Now}加入频道 uid" + uid);
Console.WriteLine($"{DateTime.Now}加入频道 tenant" + tenant);
using (var pipe = RedisHelper.Instance.StartPipe())
{
var userInfo = new ChannelUserInfo(uid, Context.ConnectionId, enableMicr, enableCamera);
pipe.HSet(RedisKeyConstant.SessionManage.GetChannelUserKey(tenant, roomNum), uid, userInfo.ToJsonString());
pipe.HIncrBy(RedisKeyConstant.SessionManage.GetChannelUserCountKey(tenant), roomNum, 1);
//pipe.HIncrBy(RedisKeyConstant.SessionManage.GetChannelUserCountKey(tenant), roomNum, 1);
pipe.HSet(RedisKeyConstant.SessionManage.GetUserJoinChannelKey(uid), roomNum, 1);
pipe.EndPipe();
}
@ -98,15 +123,15 @@ namespace WGShare.API.Hubs
var uid = Context.User?.Claims.FirstOrDefault(x => x.Type == "uid")?.Value;
await Console.Out.WriteLineAsync("离开频道 会议号:" + roomNum);
await Console.Out.WriteLineAsync("离开频道 uid" + uid);
await Console.Out.WriteLineAsync("离开频道 tenant" + tenant);
Console.WriteLine($" {DateTime.Now}离开频道 会议号:" + roomNum);
Console.WriteLine($" {DateTime.Now}离开频道 uid" + uid);
Console.WriteLine($" {DateTime.Now}离开频道 tenant" + tenant);
using (var pipe = RedisHelper.Instance.StartPipe())
{
pipe.HDel(RedisKeyConstant.SessionManage.GetChannelUserKey(tenant, roomNum), uid);
pipe.HDel(RedisKeyConstant.SessionManage.GetUserJoinChannelKey(uid), roomNum);
pipe.HIncrBy(RedisKeyConstant.SessionManage.GetChannelUserCountKey(tenant), roomNum, -1);
//pipe.HIncrBy(RedisKeyConstant.SessionManage.GetChannelUserCountKey(tenant), roomNum, -1);
pipe.EndPipe();
}
@ -124,9 +149,9 @@ namespace WGShare.API.Hubs
var uname = Context.User?.Claims.FirstOrDefault(x => x.Type == "uname")?.Value;
var uid = Context.User?.Claims.FirstOrDefault(x => x.Type == "uid")?.Value;
await Console.Out.WriteLineAsync("发送消息 uname" + uname);
await Console.Out.WriteLineAsync("发送消息 roomNum" + rooNum);
await Console.Out.WriteLineAsync("发送消息 msg" + msg);
Console.WriteLine($" {DateTime.Now}发送消息 uname" + uname);
Console.WriteLine($" {DateTime.Now}发送消息 roomNum" + rooNum);
Console.WriteLine($" {DateTime.Now}发送消息 msg" + msg);
await Clients.GroupExcept(rooNum, Context.ConnectionId).ReceiveMessage(uid, uname, msg);
}

View File

@ -21,7 +21,6 @@ namespace WGShare.API
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;

View File

@ -43,17 +43,17 @@ namespace WGShare.API.ServiceConfigs
db.Aop.OnLogExecuting = (sql, pars) =>
{
// 打印 Sql 语句
Console.WriteLine($@"{DateTime.Now.ToShortTimeString()}{new string('=', 10)}BEGIN{new string('=', 5)} DB-IP{ipMatch.Value} {new string('=', 5)} DB-Name:{dbNamne} {new string('=', 15)}");
Console.WriteLine($"执行Sql:{Environment.NewLine}{sql}");
Console.WriteLine($"参数:{db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value))}");
//Console.WriteLine($@"{DateTime.Now.ToShortTimeString()}{new string('=', 10)}BEGIN{new string('=', 5)} DB-IP{ipMatch.Value} {new string('=', 5)} DB-Name:{dbNamne} {new string('=', 15)}");
//Console.WriteLine($"执行Sql:{Environment.NewLine}{sql}");
//Console.WriteLine($"参数:{db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value))}");
};
//SQL执行完成
db.Aop.OnLogExecuted = (sql, pars) =>
{
//执行完了可以输出SQL执行时间
Console.WriteLine("Sql用时:" + db.Ado.SqlExecutionTime.ToString());
Console.WriteLine($@"{DateTime.Now.ToShortTimeString()}{new string('=', 10)}END{new string('=', 7)} DB-IP{ipMatch.Value} {new string('=', 5)} DB-Name:{dbNamne} {new string('=', 15)}");
//Console.WriteLine("Sql用时:" + db.Ado.SqlExecutionTime.ToString());
//Console.WriteLine($@"{DateTime.Now.ToShortTimeString()}{new string('=', 10)}END{new string('=', 7)} DB-IP{ipMatch.Value} {new string('=', 5)} DB-Name:{dbNamne} {new string('=', 15)}");
};
}
});

View File

@ -3,6 +3,24 @@
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
},
"Console": {
//"LogLevel": {
// "Default": "Information",
// "Microsoft": "Warning",
//},
"FormatterName": "CustomTimePrefixingFormatter",
"FormatterOptions": {
"CustomPrefix": "|-<[",
"CustomSuffix": "]>-|",
"SingleLine": true,
"IncludeScopes": true,
"TimestampFormat": "HH:mm:ss.ffff ",
"UseUtcTimestamp": true,
"JsonWriterOptions": {
"Indented": true
}
}
}
},
"ConnectionStrings": {

View File

@ -41,6 +41,7 @@ namespace WGShare.Domain.Constant
/// </summary>
/// <param name="tenantId"></param>
/// <returns></returns>
[Obsolete("废弃")]
public static string GetChannelUserCountKey(string tenantId) => $@"te_{tenantId}:ChannelUserCount";
}
}

View File

@ -23,6 +23,6 @@ namespace WGShare.Domain.DTOs.Room
/// <summary>
/// 在线人数
/// </summary>
public int OnlineUserCount { get; set; }
public long OnlineUserCount { get; set; }
}
}