2021-11-28 14:18:21 +01:00
|
|
|
|
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;
|
|
|
|
|
|
2021-12-18 12:18:35 +01:00
|
|
|
|
public string? QueueName { get; private set; }
|
|
|
|
|
public string? Exchange { get; }
|
|
|
|
|
public string? RoutingKey { get; }
|
2021-11-28 14:18:21 +01:00
|
|
|
|
public event EventHandler<MessageReceivedEventArgs>? MessageReceived;
|
|
|
|
|
|
|
|
|
|
|
2021-12-18 12:18:35 +01:00
|
|
|
|
public RabbitMQClientSubscriber(IModel? model, string? exchange, string? routingKey)
|
2021-11-28 14:18:21 +01:00
|
|
|
|
{
|
|
|
|
|
this.model = model;
|
|
|
|
|
Exchange = exchange;
|
|
|
|
|
RoutingKey = routingKey;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public ValueTask DisposeAsync()
|
|
|
|
|
{
|
2021-12-18 12:18:35 +01:00
|
|
|
|
GC.SuppressFinalize(this);
|
|
|
|
|
|
2021-11-28 14:18:21 +01:00
|
|
|
|
if (model != null && consumerTag != null && model.IsOpen)
|
|
|
|
|
model.BasicCancelNoWait(consumerTag);
|
|
|
|
|
|
|
|
|
|
return default;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public void Start()
|
|
|
|
|
{
|
|
|
|
|
started = true;
|
|
|
|
|
if (model == null)
|
|
|
|
|
return;
|
|
|
|
|
|
2021-12-18 12:18:35 +01:00
|
|
|
|
QueueName = model.QueueDeclare().QueueName;
|
|
|
|
|
if (Exchange != null && RoutingKey != null)
|
|
|
|
|
model.QueueBind(QueueName, Exchange, RoutingKey);
|
2021-11-28 14:18:21 +01:00
|
|
|
|
|
|
|
|
|
var consumer = new EventingBasicConsumer(model);
|
|
|
|
|
consumer.Received += ClientReceived;
|
|
|
|
|
|
2021-12-18 12:18:35 +01:00
|
|
|
|
consumerTag = model.BasicConsume(QueueName, true, consumer);
|
2021-11-28 14:18:21 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 14:08:29 +01:00
|
|
|
|
new ReceivedMessageInfo(
|
2021-11-28 14:18:21 +01:00
|
|
|
|
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
|
|
|
|
|
)
|
|
|
|
|
));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
}
|