1
0
mirror of synced 2024-11-22 12:43:51 +00:00
PettingZoo/PettingZoo.RabbitMQ/RabbitMQClientSubscriber.cs

84 lines
2.3 KiB
C#
Raw Normal View History

using System;
using System.Threading.Tasks;
using PettingZoo.Core.Connection;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
namespace PettingZoo.RabbitMQ
{
public class RabbitMQClientSubscriber : ISubscriber
{
private IModel? model;
private string? consumerTag;
private bool started;
public string? QueueName { get; private set; }
public string? Exchange { get; }
public string? RoutingKey { get; }
public event EventHandler<MessageReceivedEventArgs>? MessageReceived;
public RabbitMQClientSubscriber(IModel? model, string? exchange, string? routingKey)
{
this.model = model;
Exchange = exchange;
RoutingKey = routingKey;
}
public ValueTask DisposeAsync()
{
GC.SuppressFinalize(this);
if (model != null && consumerTag != null && model.IsOpen)
model.BasicCancelNoWait(consumerTag);
return default;
}
public void Start()
{
started = true;
if (model == null)
return;
QueueName = model.QueueDeclare().QueueName;
if (Exchange != null && RoutingKey != null)
model.QueueBind(QueueName, Exchange, RoutingKey);
var consumer = new EventingBasicConsumer(model);
consumer.Received += ClientReceived;
consumerTag = model.BasicConsume(QueueName, true, consumer);
}
public void Connected(IModel newModel)
{
model = newModel;
if (started)
Start();
}
private void ClientReceived(object? sender, BasicDeliverEventArgs args)
{
MessageReceived?.Invoke(this, new MessageReceivedEventArgs(
2021-12-06 13:08:29 +00:00
new ReceivedMessageInfo(
args.Exchange,
args.RoutingKey,
args.Body.ToArray(),
RabbitMQClientPropertiesConverter.Convert(args.BasicProperties),
args.BasicProperties.Timestamp.UnixTime > 0
? DateTimeOffset.FromUnixTimeSeconds(args.BasicProperties.Timestamp.UnixTime).LocalDateTime
: DateTime.Now
)
));
}
}
}