46 lines
1.6 KiB
C#
46 lines
1.6 KiB
C#
using IM_API.Domain.Events;
|
|
using IM_API.Dtos;
|
|
using IM_API.Hubs;
|
|
using IM_API.Tools;
|
|
using IM_API.VOs.Group;
|
|
using MassTransit;
|
|
using Microsoft.AspNetCore.SignalR;
|
|
using StackExchange.Redis;
|
|
|
|
namespace IM_API.Application.EventHandlers.GroupJoinHandler
|
|
{
|
|
public class GroupJoinSignalrHandler : IConsumer<GroupJoinEvent>
|
|
{
|
|
private readonly IHubContext<ChatHub> _hub;
|
|
private readonly IDatabase _redis;
|
|
public GroupJoinSignalrHandler(IHubContext<ChatHub> hub, IConnectionMultiplexer connectionMultiplexer)
|
|
{
|
|
_hub = hub;
|
|
_redis = connectionMultiplexer.GetDatabase();
|
|
}
|
|
|
|
public async Task Consume(ConsumeContext<GroupJoinEvent> context)
|
|
{
|
|
var @event = context.Message;
|
|
string stramKey = StreamKeyBuilder.Group(@event.GroupId);
|
|
//将用户加入群组通知
|
|
var list = await _redis.SetMembersAsync(RedisKeys.GetConnectionIdKey(@event.UserId.ToString()));
|
|
if(list != null && list.Length > 0)
|
|
{
|
|
var tasks = list.Select(connectionId =>
|
|
_hub.Groups.AddToGroupAsync(connectionId!, stramKey)
|
|
).ToList();
|
|
|
|
await Task.WhenAll(tasks);
|
|
}
|
|
//发送通知给群成员
|
|
var msg = new GroupJoinVo
|
|
{
|
|
GroupId = @event.GroupId,
|
|
UserId = @event.UserId
|
|
};
|
|
await _hub.Clients.Group(stramKey).SendAsync("ReceiveMessage",new HubResponse<GroupJoinVo>("Event",msg));
|
|
}
|
|
}
|
|
}
|