namespace ZhiYi.Core.Application.RedisServices
{
///
/// Redis订阅/发布
///
public class SubscribeAndPublishService
{
private readonly IConnectionMultiplexer _redisConnectionMultiplexer;
private readonly ConcurrentDictionary _subscriptions = new();
private readonly ILogger _logger;
public SubscribeAndPublishService(IConnectionMultiplexer connectionMultiplexer, ILogger logger)
{
_redisConnectionMultiplexer = connectionMultiplexer;
_logger = logger;
}
///
/// 订阅
///
///
public void Subscribe(string clientId, IWebSocket socket)
{
try
{
var subscriber = _redisConnectionMultiplexer.GetSubscriber();
var channel = "notifications:" + clientId;//频道可拓展为动态
_logger.LogInformation("开始订阅 'notifications' 频道, clientID为 {clientId}", clientId);
var handler = new Action(async (ch, value) =>
{
var notification = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(value));
if (notification != null && notification.ClientId == clientId)
{
_logger.LogInformation("订阅到 'notifications' 频道, clientID为 {clientId}", clientId);
//await _hubContext.Clients.Client(clientId).SendAsync("ReceiveNotification", notification.Message);
await socket.SendAsync(notification.Message);
}
});
subscriber.Subscribe(channel, handler);
_subscriptions[clientId] = (subscriber, channel);
}
catch (Exception ex)
{
_logger.LogError("订阅出错, {message}", ex.Message);
}
}
///
/// 发布
///
///
///
public void Publish(string message, string clientId)
{
try
{
var notification = new Notification { Message = message, ClientId = clientId };
var serializedMessage = JsonConvert.SerializeObject(notification);
var bytes = Encoding.UTF8.GetBytes(serializedMessage);
var publisher = _redisConnectionMultiplexer.GetSubscriber();
publisher.Publish(channel: "notifications:" + clientId, message: bytes);
}
catch (Exception ex)
{
_logger.LogError("发布出错, {message}", ex.Message);
}
}
///
/// 取消订阅
///
///
public void Unsubscribe(string clientId)
{
if (_subscriptions.TryGetValue(clientId, out var value))
{
value.subscriber.Unsubscribe(value.redisChannel + ":" + clientId);
_ = _subscriptions.TryRemove(clientId, out var sub);
}
}
}
///
/// 消息管道内容
///
public class Notification
{
///
/// 消息
///
public string Message { get; set; }
///
/// 客户端ID
///
public string ClientId { get; set; }
///
/// 连接信息
///
public IWebSocket webSocket { get; set; }
}
}