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