using System.Threading.Channels;
namespace Admin.NET.Core.Ai.Services.SSE;
///
/// SSE通道管理
///
public class SseChannelManager: ISingleton
{
private readonly ConcurrentDictionary> _userChannels = new();
///
/// 注册
///
///
///
public ChannelReader Register(long userId)
{
var channel = Channel.CreateBounded(new BoundedChannelOptions(100){
FullMode = BoundedChannelFullMode.Wait
});
_userChannels[userId] = channel;
return channel.Reader;
}
///
/// 注销
///
///
public void Unregister(long userId)
{
if (_userChannels.TryRemove(userId, out var channel))
{
channel.Writer.TryComplete(); // 结束读端
}
}
///
/// 发送消息
///
///
///
///
public async Task SendMessageAsync(long userId, string message, CancellationToken cancellationToken = default)
{
if (_userChannels.TryGetValue(userId, out var channel))
{
await channel.Writer.WriteAsync(message,cancellationToken);
}
}
}