/// <summary> /// Get messages from the queue. /// </summary> /// <param name="millisecondsTimeout">The wait timeout in milliseconds for a message to arrive. -1 for infinite timeout</param> /// <param name="noAck">If the acknowledgement will be manual (noAck == false) or automatic (true).</param> public IEnumerable <RabbitWorkMessage> Get(int millisecondsTimeout, bool noAck = false) { RabbitMQ.Client.Events.BasicDeliverEventArgs item; bool done = false; while (!done) { done = true; using (var sub = new RabbitMQ.Client.MessagePatterns.Subscription(ConsumerChannel, QueueName, noAck)) { while (sub.Next(millisecondsTimeout, out item)) { if (item == null) { // in case of a connection close, the item will be null and we should re-subscribe done = false; break; } // if the message is within the retry threshold, proceed... var msg = new RabbitWorkMessage(this, item); if (CheckRetryLimit(_maxRetry, msg)) { yield return(msg); } } } } }
static void Subscribe(IConnection connection, string exchangeName, string routingKey) { new Thread(() => { var channel = connection.CreateModel(); var queueDeclareOk = channel.QueueDeclare(); channel.QueueBind(queueDeclareOk.QueueName, exchangeName, routingKey); var subscription = new RabbitMQ.Client.MessagePatterns.Subscription(channel, queueDeclareOk.QueueName); try { while (!tokenSource.IsCancellationRequested && channel.IsOpen) { var deliveryArgs = subscription.Next(); if (!(deliveryArgs == null || tokenSource.IsCancellationRequested)) { deliveryQueue.Add(deliveryArgs, tokenSource.Token); } } } // deliveryQueue has been disposed, so do nothing catch (OperationCanceledException) {} catch (ObjectDisposedException) {} Console.Out.WriteLine("Subscription to exchange {0}, routingKey {1} closed", exchangeName, routingKey); }) { Name = string.Format("EasyNetQ.Trace - subscription {0} {1}", exchangeName, routingKey) }.Start(); }
public IDisposable Subscribe(IObserver <string> observer) { var disposed = false; new System.Threading.Thread(state => { var model = connection.CreateModel(); var subscription = new RabbitMQ.Client.MessagePatterns.Subscription(model, queue, false); while (!disposed) { var deliverEventArgs = subscription.Next(); if (deliverEventArgs != null) { var message = Encoding.UTF8.GetString(deliverEventArgs.Body); Log.WriteLine("Before running observer"); observer.OnNext(message); Log.WriteLine("After running observer"); subscription.Ack(deliverEventArgs); } } }) { Name = "Subscription" }.Start(); return(Disposable.Create(() => { disposed = true; observer.OnCompleted(); })); }
protected override void StartQueue(object obj) { var queue = obj as Queue; if(queue == null) throw new Exception("This is not a queue."); var subscribtion = new RabbitMQ.Client.MessagePatterns.Subscription(Connection.Current.CreateModel(), queue.Name); new RpcServer(MessageHandlerProvider, subscribtion, Queue).MainLoop(); }
public void It_should_sent_messages_which_will_be_received() { var model1 = ComponentLocator.Current.Get<IModel>(); var publisher = new MessagePublisher(model1, new MessageFormatter(new Utf8MessageSerializer(null), new JsonMessageStringifier(null), null), new ResponseAwaiter(new MessageFormatter(new Utf8MessageSerializer(null), new JsonMessageStringifier(null), null ), null ), null); publisher.Publish(new SampleMessage(){ Message = "Hello"}, "TestQueue1_1" ); var model = ComponentLocator.Current.Get<IModel>(); var subs = new RabbitMQ.Client.MessagePatterns.Subscription(model, "TestQueue1_1"); var args = subs.Next(); var messageFormatter = new MessageFormatter(new Utf8MessageSerializer(null), new JsonMessageStringifier(null), null); var obj = messageFormatter.Deformat(args.Body); obj.Should().NotBeNull(); obj.Should().BeOfType<SampleMessage>(); ((SampleMessage) obj).Message.Should().Be("Hello"); subs.Close(); }
private static void RabbitListener() { IModel model = GetRabbitChannel(exchangeName, queueName, routingKey); var subscription = new RabbitMQ.Client.MessagePatterns.Subscription(model, queueName, false); while (true) { var basicDeliveryEventArgs = subscription.Next(); string messageContent = Encoding.UTF8.GetString(basicDeliveryEventArgs.Body); // action try { var computer = System.Text.Json.JsonSerializer.Deserialize <Computer>(messageContent); HandleMessage(computer); } catch (Exception e) { HandleMessage(messageContent); } subscription.Ack(basicDeliveryEventArgs); } }
static void Subscribe(IConnection connection, string exchangeName, string routingKey) { new Thread(() => { var channel = connection.CreateModel(); var queueDeclareOk = channel.QueueDeclare(); channel.QueueBind(queueDeclareOk.QueueName, exchangeName, routingKey); var subscription = new RabbitMQ.Client.MessagePatterns.Subscription(channel, queueDeclareOk.QueueName); try { while (!tokenSource.IsCancellationRequested && channel.IsOpen) { var deliveryArgs = subscription.Next(); if (!(deliveryArgs == null || tokenSource.IsCancellationRequested)) { deliveryQueue.Add(deliveryArgs, tokenSource.Token); } } } // deliveryQueue has been disposed, so do nothing catch (OperationCanceledException) {} catch (ObjectDisposedException) {} Console.Out.WriteLine("Subscription to exchange {0}, routingKey {1} closed", exchangeName, routingKey); }) { Name = string.Format("EasyNetQ.Trace - subscription {0} {1}", exchangeName, routingKey) }.Start(); }
private void StartAnonymousQueueListener(object state) { var queueName = (string)state; if (Log.IsInfoEnabled) Log.Info("Starting listening on awaiter queue: {0}", queueName); var model = ComponentLocator.Current.Get<IModel>(); var subscription = new RabbitMQ.Client.MessagePatterns.Subscription(model, queueName); _isListenerRunning = true; OnAwaiterInitialized(); while (_isListenerRunning) { BasicDeliverEventArgs delivery; if(subscription.Next(100, out delivery)) { if(Log.IsDebugEnabled) Log.Debug("Checking for delivery..."); if(delivery == null) continue; if (delivery.BasicProperties == null) continue; var correlationId = delivery.BasicProperties.CorrelationId; if(Log.IsInfoEnabled) Log.Info("Received reply with CorrelationId: {0}"); Action<IMessage> resultAction; if(_responseHandlers.TryGetValue(correlationId, out resultAction)) { if(Log.IsInfoEnabled) Log.Info("Found reply action for reply with CorrelationId: {0}", correlationId); var message = _messageFormatter.Deformat(delivery.Body) as IMessage; if(message != null) { if(Log.IsInfoEnabled) Log.Info("Executing reply action."); resultAction(message); if (Log.IsInfoEnabled) Log.Info("Executed reply action."); } _responseHandlers.Remove(correlationId); } } } }
protected override void StartQueue(object queueObj) { try { if (Log.IsDebugEnabled) Log.Debug("Starting queue listened on thread: {0}", Thread.CurrentThread.ManagedThreadId); var queue = (Queue)queueObj; var subscription = new RabbitMQ.Client.MessagePatterns.Subscription(Connection.Current.CreateModel(), queue.Name, !queue.RequiresAck); while (true) { var msg = subscription.Next(); if(Log.IsInfoEnabled) Log.Info("Received new message {0}", msg.DeliveryTag); Queue.Enqueue(new RabbitMessage(msg.Body, msg.BasicProperties)); } } catch (Exception ex) { Log.Error("Exception in queue handling", ex); } }