private async ValueTask CreateReceiverConsumerAsync() { if (_receiverConsumer != null) { return; } if (_receiver is null) { return; } using (await _locker.LockAsync().ConfigureAwait(false)) { if (_receiverConsumer != null) { return; } if (_receiver is null) { return; } await _receiver.EnsureConnectionAsync(5000, int.MaxValue).ConfigureAwait(false); _receiver.EnsureQueue(); _receiverConsumer = new EventingBasicConsumer(_receiver.Channel); _receiverConsumer.Received += MessageReceivedHandler; var rcvName = _receiver.Name; if (!UseSingleResponseQueue) { rcvName += "-" + Core.InstanceIdString; _receiver.Channel.QueueDeclare(rcvName, false, false, true, null); } _receiverConsumerTag = _receiver.Channel.BasicConsume(rcvName, false, _receiverConsumer); Core.Log.LibVerbose("The Receiver for the queue \"{0}\" has been created.", rcvName); } }
/// <inheritdoc /> /// <summary> /// Delete a message queue /// </summary> /// <param name="queue">Message Queue connection instance</param> /// <returns>true if the message queue was deleted; otherwise, false.</returns> public bool Delete(MQConnection queue) { var rabbitQueue = new RabbitMQueue(queue); rabbitQueue.EnsureConnectionAsync(2000, 100).WaitAndResults(); rabbitQueue.Channel.QueueDelete(queue.Name, false, false); rabbitQueue.Close(); return(true); }
/// <inheritdoc /> /// <summary> /// Purge all messages from a message queue /// </summary> /// <param name="queue">Message Queue connection instance</param> public void Purge(MQConnection queue) { if (!Exist(queue)) { return; } var rabbitQueue = new RabbitMQueue(queue); rabbitQueue.EnsureConnectionAsync(2000, 100).WaitAndResults(); rabbitQueue.Channel.QueuePurge(queue.Name); rabbitQueue.Close(); }
/// <inheritdoc /> /// <summary> /// Check if the message queue exists /// </summary> /// <param name="queue">Message Queue connection instance</param> /// <returns>true if the message queue exists; otherwise, false.</returns> public bool Exist(MQConnection queue) { var rabbitQueue = new RabbitMQueue(queue); rabbitQueue.EnsureConnectionAsync(2000, 100).WaitAndResults(); try { var result = rabbitQueue.Channel.QueueDeclarePassive(queue.Name); rabbitQueue.Close(); return(result != null); } catch { return(false); } }
/// <inheritdoc /> /// <summary> /// Create a new message queue /// </summary> /// <param name="queue">Message Queue connection instance</param> /// <returns>true if the message queue was created; otherwise, false.</returns> public bool Create(MQConnection queue) { if (Exist(queue)) { return(false); } var rabbitQueue = new RabbitMQueue(queue); if (!rabbitQueue.EnsureConnectionAsync(2000, 100).WaitAndResults()) { return(false); } rabbitQueue.EnsureQueue(); rabbitQueue.EnsureExchange(); rabbitQueue.Close(); return(true); }
protected override async Task OnListenerTaskStartAsync(CancellationToken token) { _token = token; _receiver = new RabbitMQueue(Connection); await _receiver.EnsureConnectionAsync(5000, int.MaxValue).ConfigureAwait(false); _receiver.EnsureQueue(); _receiverConsumer = new EventingBasicConsumer(_receiver.Channel); _receiverConsumer.Received += MessageReceivedHandler; _receiverConsumerTag = _receiver.Channel.BasicConsume(_receiver.Name, false, _receiverConsumer); _monitorTask = Task.Run(MonitorProcess, _token); await token.WhenCanceledAsync().ConfigureAwait(false); if (_receiverConsumerTag != null) { _receiver.Channel.BasicCancel(_receiverConsumerTag); } _receiver.Close(); await _monitorTask.ConfigureAwait(false); }
private async Task MonitorProcess() { while (!_token.IsCancellationRequested) { try { if (Interlocked.CompareExchange(ref _exceptionSleep, 0, 1) == 1) { if (_receiverConsumerTag != null) { _receiver.Channel.BasicCancel(_receiverConsumerTag); } _receiver.Close(); Core.Log.Warning("An exception has been thrown, the listener has been stopped for {0} seconds.", Config.RequestOptions.ServerReceiverOptions.SleepOnExceptionInSec); await Task.Delay(Config.RequestOptions.ServerReceiverOptions.SleepOnExceptionInSec * 1000, _token).ConfigureAwait(false); await _receiver.EnsureConnectionAsync(5000, int.MaxValue).ConfigureAwait(false); _receiverConsumerTag = _receiver.Channel.BasicConsume(_receiver.Name, false, _receiverConsumer); Core.Log.Warning("The listener has been resumed."); } if (Counters.CurrentMessages >= Config.RequestOptions.ServerReceiverOptions.MaxSimultaneousMessagesPerQueue && !_token.IsCancellationRequested) { if (_receiverConsumerTag != null) { _receiver.Channel.BasicCancel(_receiverConsumerTag); } Core.Log.Warning("Maximum simultaneous messages per queue has been reached, the message needs to wait to be processed, consider increase the MaxSimultaneousMessagePerQueue value, CurrentValue={0}.", Config.RequestOptions.ServerReceiverOptions.MaxSimultaneousMessagesPerQueue); while (!_token.IsCancellationRequested && Counters.CurrentMessages >= Config.RequestOptions.ServerReceiverOptions.MaxSimultaneousMessagesPerQueue) { await Task.Delay(500, _token).ConfigureAwait(false); } _receiverConsumerTag = _receiver.Channel.BasicConsume(_receiver.Name, false, _receiverConsumer); Core.Log.Warning("The listener has been resumed."); } if (!_receiver.Channel.IsOpen && !_token.IsCancellationRequested) { Core.Log.Warning("The Receiver channel is closed and should be open, reconnecting."); _receiver.Close(); await _receiver.EnsureConnectionAsync(5000, int.MaxValue).ConfigureAwait(false); if (_receiverConsumerTag != null) { _receiver.Channel.BasicCancel(_receiverConsumerTag); } _receiverConsumerTag = _receiver.Channel.BasicConsume(_receiver.Name, false, _receiverConsumer); Core.Log.Warning("The listener has been resumed."); } await Task.Delay(1000, _token).ConfigureAwait(false); } catch (TaskCanceledException) { } catch (Exception ex) { Core.Log.Write(ex); if (!_token.IsCancellationRequested) { await Task.Delay(2000, _token).ConfigureAwait(false); } } } }
protected override void OnInit() { OnDispose(); _senders = new List <RabbitMQueue>(); _receiver = null; _receiverStopBuffered = ActionDelegate.Create(RemoveReceiverConsumer).CreateBufferedAction(60000); if (Config != null) { if (Config.ClientQueues != null) { _clientQueues = Config.ClientQueues.FirstOf( c => c.EnvironmentName?.SplitAndTrim(",").Contains(Core.EnvironmentName) == true && c.MachineName?.SplitAndTrim(",").Contains(Core.MachineName) == true, c => c.EnvironmentName?.SplitAndTrim(",").Contains(Core.EnvironmentName) == true, c => c.MachineName?.SplitAndTrim(",").Contains(Core.MachineName) == true, c => c.EnvironmentName.IsNullOrWhitespace()); } _senderOptions = Config.RequestOptions?.ClientSenderOptions; _receiverOptions = Config.ResponseOptions?.ClientReceiverOptions; _receiverOptionsTimeout = TimeSpan.FromSeconds(_receiverOptions?.TimeoutInSec ?? 20); UseSingleResponseQueue = _receiverOptions?.Parameters?[ParameterKeys.SingleResponseQueue].ParseTo(true) ?? true; if (_clientQueues != null) { if (_clientQueues.SendQueues?.Any() == true) { foreach (var queue in _clientQueues.SendQueues) { var rabbitQueue = new RabbitMQueue(queue); rabbitQueue.EnsureConnectionAsync(2000, int.MaxValue).WaitAndResults(); rabbitQueue.EnsureExchange(); _senders.Add(rabbitQueue); } } if (_clientQueues.RecvQueue != null && !SendOnly) { _receiver = new RabbitMQueue(_clientQueues.RecvQueue); } } if (_senderOptions is null) { throw new Exception("Client Sender Options is Null."); } _priority = (byte)(_senderOptions.MessagePriority == MQMessagePriority.High ? 9 : _senderOptions.MessagePriority == MQMessagePriority.Low ? 1 : 5); _expiration = (_senderOptions.MessageExpirationInSec * 1000).ToString(); _deliveryMode = (byte)(_senderOptions.Recoverable ? 2 : 1); CreateReceiverConsumerAsync().WaitAsync(); } Core.Status.Attach(collection => { if (_senders != null) { for (var i = 0; i < _senders.Count; i++) { collection.Add("Sender: {0} ".ApplyFormat(i), _senders[i].Route + " - " + _senders[i].Name); } } if (_receiver != null) { collection.Add("Receiver: {0}", _receiver.Route + " - " + _receiver.Name); } }); }