public Next ( ) : RabbitMQ.Client.Events.BasicDeliverEventArgs | ||
Результат | RabbitMQ.Client.Events.BasicDeliverEventArgs |
///<summary>Retrieves the reply for the request with the given ///correlation ID from our internal Subscription.</summary> ///<remarks> /// Currently requires replies to arrive in the same order as /// the requests were sent out. Subclasses may override this /// to provide more sophisticated behaviour. ///</remarks> protected virtual BasicDeliverEventArgs RetrieveReply(string correlationId) { BasicDeliverEventArgs reply; if (!Subscription.Next(TimeoutMilliseconds, out reply)) { OnTimedOut(); return(null); } if (reply == null) { OnDisconnected(); return(null); } if (reply.BasicProperties.CorrelationId != correlationId) { throw new ProtocolViolationException (string.Format("Wrong CorrelationId in reply; expected {0}, got {1}", correlationId, reply.BasicProperties.CorrelationId)); } Subscription.Ack(reply); return(reply); }
public void ProcessMessages() { using (_connection = _factory.CreateConnection()) { using (var channel = _connection.CreateModel()) { Console.WriteLine("Listening for Topic <payment.purchaseorder>"); Console.WriteLine("------------------------------------------"); Console.WriteLine(); channel.ExchangeDeclare(ExchangeName, "topic"); channel.QueueDeclare(PurchaseOrderQueueName, true, false, false, null); channel.QueueBind(PurchaseOrderQueueName, ExchangeName, "payment.purchaseorder"); channel.BasicQos(0, 10, false); Subscription subscription = new Subscription(channel, PurchaseOrderQueueName, false); while (true) { BasicDeliverEventArgs deliveryArguments = subscription.Next(); var message = (PurchaseOrder)deliveryArguments.Body.DeSerialize(typeof(PurchaseOrder)); var routingKey = deliveryArguments.RoutingKey; Console.WriteLine("-- Purchase Order - Routing Key <{0}> : {1}, £{2}, {3}, {4}", routingKey, message.CompanyName, message.AmountToPay, message.PaymentDayTerms, message.PoNumber); subscription.Ack(deliveryArguments); } } } }
public void ProcessMessages() { using (_connection = _factory.CreateConnection()) { using (var channel = _connection.CreateModel()) { Console.WriteLine("Listening for Topic <payment.*>"); Console.WriteLine("------------------------------"); Console.WriteLine(); channel.ExchangeDeclare(ExchangeName, "topic"); channel.QueueDeclare(AllQueueName, true, false, false, null); channel.QueueBind(AllQueueName, ExchangeName, "payment.*"); channel.BasicQos(0, 10, false); Subscription subscription = new Subscription(channel, AllQueueName, false); while (true) { BasicDeliverEventArgs deliveryArguments = subscription.Next(); var message = deliveryArguments.Body.DeSerializeText(); Console.WriteLine("Message Received '{0}'", message); subscription.Ack(deliveryArguments); } } } }
public void Subscribe(string queueName, Action<string> callback) { this.Subscriptions = this.Subscriptions ?? Enumerable.Empty<Task>(); this.Subscriptions = this.Subscriptions.Concat(new[] { Task.Factory.StartNew(delegate { var factory = new ConnectionFactory() { VirtualHost = "/", HostName = "127.0.0.1", Port = AmqpTcpEndpoint.UseDefaultPort }; factory.UserName = "******"; factory.Password = "******"; using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { var subscription = new Subscription(channel, queueName, false); while(true) { var eventArgs = subscription.Next(); var content = eventArgs == null ? string.Empty : Encoding.UTF8.GetString(eventArgs.Body); subscription.Ack(eventArgs); callback(content); } } } } )}); }
public void StartListening(Action<byte[], IDictionary<string, object>> onMessage) { if (this.IsListening) throw new InvalidOperationException("Client is already listening for messages"); Action subscribeAction = () => { try { subscriptionLifetimeResetEvent.Reset(); Subscription subscriptionHandler = new Subscription(this.Connection.GetModel(), this.QueueName); int waitForMessagesTimeout = 100; this.loopControlResetEvent.Reset(); while (!loopControlResetEvent.IsSet) { try { BasicDeliverEventArgs delivery = null; if (subscriptionHandler.Next(waitForMessagesTimeout, out delivery)) { if (delivery == null) continue; // Deliver message var p = CreateProperties(delivery); onMessage(delivery.Body, p); } } catch (ThreadAbortException) { // Nothing to do, thread is being aborted. // Set the reset event to leave gracefully loopControlResetEvent.Set(); } catch (Exception) { // Any other exception should be ignored. } } // Close the subscription if its still open if (subscriptionHandler.Model.IsOpen) { subscriptionHandler.Close(); } } finally { subscriptionLifetimeResetEvent.Set(); } }; this.currentSubscription = subscribeAction; }
public void TestChannelClosureIsObservableOnSubscription() { string q = Model.QueueDeclare(); Subscription sub = new Subscription(Model, q, true); BasicDeliverEventArgs r1; Assert.IsFalse(sub.Next(100, out r1)); Model.BasicPublish("", q, null, enc.GetBytes("a message")); Model.BasicPublish("", q, null, enc.GetBytes("a message")); BasicDeliverEventArgs r2; Assert.IsTrue(sub.Next(1000, out r2)); Assert.IsNotNull(sub.Next()); Model.Close(); Assert.IsNull(sub.Next()); BasicDeliverEventArgs r3; Assert.IsFalse(sub.Next(100, out r3)); }
private int OneConsumer() { using (var connection = Helpers.CreateConnectionToSecondaryVirtualHostOnAlternativePort()) using (var model = connection.CreateModel()) { var queue = model.QueueDeclare(); model.QueueBind(queue, Constants.FederationExchangeName, "#"); var subscription = new Subscription(model, queue, true); consumerReady.Set(); return subscription.Next().Body.Integer(); } }
private static void blockingReceiveMessages(Subscription sub, long msgCount) { Console.WriteLine("Receiving {0} messages (using a Subscriber)", msgCount); for (int i = 0; i < msgCount; ++i) { Console.WriteLine("Message {0}: {1} (via Subscription.Next())", i, messageText(sub.Next())); Console.WriteLine("Message {0} again: {1} (via Subscription.LatestEvent)", i, messageText(sub.LatestEvent)); sub.Ack(); } Console.WriteLine("Done.\n"); }
private void Consume() { bool autoAck = false; //create a subscription mSubscription = new Subscription(Model, QueueName, autoAck); while (isConsuming) { BasicDeliverEventArgs e = mSubscription.Next(); byte[] body = e.Body; onMessageReceived(body); mSubscription.Ack(e); } }
static void Main() { // Set up the RabbitMQ connection and channel var connectionFactory = new ConnectionFactory { HostName = "localhost", Port = 5672, UserName = "******", Password = "******", Protocol = Protocols.AMQP_0_9_1, RequestedFrameMax = UInt32.MaxValue, RequestedHeartbeat = UInt16.MaxValue }; using (var connection = connectionFactory.CreateConnection()) { using (var channel = connection.CreateModel()) { // This instructs the channel not to prefetch more than one message channel.BasicQos(0, 1, false); // Create a new, durable exchange channel.ExchangeDeclare("sample-ex", ExchangeType.Direct, true, false, null); // Create a new, durable queue channel.QueueDeclare("sample-queue", true, false, false, null); // Bind the queue to the exchange channel.QueueBind("sample-queue", "sample-ex", "optional-routing-key"); using (var subscription = new Subscription(channel, "sample-queue", false)) { Console.WriteLine("Waiting for messages..."); var encoding = new UTF8Encoding(); while (channel.IsOpen) { BasicDeliverEventArgs eventArgs; var success = subscription.Next(2000, out eventArgs); if (success == false) continue; var msgBytes = eventArgs.Body; var message = encoding.GetString(msgBytes); Console.WriteLine(message); channel.BasicAck(eventArgs.DeliveryTag, false); } } } } }
/// <remarks> /// RabbitMq does not have a Peek feature, the solution is to dequeue all messages /// without acknowledging them (noAck = true). After all messages have been read /// we dispose the RabbitMqJobQueue causing the channel to close. All unack'd /// messages then get requeued in order. /// </remarks> public IEnumerable<int> GetEnqueuedJobIds(string queue, int @from, int perPage) { using (var client = new RabbitMqJobQueue(new[] {queue}, _factory)) { var consumer = new Subscription(client.Channel, queue, true); List<int> jobIds = new List<int>(); BasicDeliverEventArgs delivery; while (consumer.Next(1000, out delivery)) { var body = Encoding.UTF8.GetString(delivery.Body); jobIds.Add(Convert.ToInt32(body)); } return jobIds.Skip(@from).Take(perPage); } }
public static IEnumerable<LogData> GetAllMessages() { using (IConnection connection = SetUpFixture.ConnectionFactory.CreateConnection()) { using (IModel model = connection.CreateModel()) { var subscription = new Subscription(model, SetUpFixture.QueueName); BasicDeliverEventArgs basicDeliveryEventArgs; while (subscription.Next(1000, out basicDeliveryEventArgs)) { var logs = (Body) XmlSerializer.Deserialize(new MemoryStream(basicDeliveryEventArgs.Body)); foreach (var entry in logs.LogDatas) { yield return entry; } } } } }
public void Listen() { Console.WriteLine("Creating channel..."); using (IModel model = conn.CreateModel()) { var subscription = new Subscription(model, "queue", false); //while (true) //{ BasicDeliverEventArgs basicDeliveryEventArgs = subscription.Next(); var command = StreamExtension.Deserialize<Vaccine.Core.Cqrs.Commands.DomainCommand>(basicDeliveryEventArgs.Body); //Encoding.UTF8.GetString(basicDeliveryEventArgs.Body); //Console.WriteLine(((CreateCommand)messageContent).Name); bus.Send(command); subscription.Ack(basicDeliveryEventArgs); //} } }
public void ReceiveHeadersMessageReceiverOne(IModel model) { model.BasicQos(0, 1, false); Subscription subscription = new Subscription(model, _headersQueueOne, false); while (true) { BasicDeliverEventArgs deliveryArguments = subscription.Next(); StringBuilder messageBuilder = new StringBuilder(); String message = Encoding.UTF8.GetString(deliveryArguments.Body); messageBuilder.Append("Message from queue: ").Append(message).Append(". "); foreach (string headerKey in deliveryArguments.BasicProperties.Headers.Keys) { byte[] value = deliveryArguments.BasicProperties.Headers[headerKey] as byte[]; messageBuilder.Append("Header key: ").Append(headerKey).Append(", value: ").Append(Encoding.UTF8.GetString(value)).Append("; "); } Console.WriteLine(messageBuilder.ToString()); subscription.Ack(deliveryArguments); } }
public static void Main(string[] args) { var connectionFactory = new ConnectionFactory {HostName = Settings.RabbitMqHost}; using (var connection = connectionFactory.CreateConnection()) { using (var model = connection.CreateModel()) { var subscription = new Subscription(model, Settings.RabbitMqQueue, false); while (true) { var basicDeliveryEventArgs = subscription.Next(); var messageContent = basicDeliveryEventArgs.Body.To<SimpleMessage>(); System.Console.WriteLine(messageContent.Content); subscription.Ack(basicDeliveryEventArgs); } } } System.Console.ReadLine(); }
public void ProcessMessages() { using (_connection = _factory.CreateConnection()) { using (var channel = _connection.CreateModel()) { Console.WriteLine("Listening for Topic <payment.cardpayment>"); Console.WriteLine("-----------------------------------------"); Console.WriteLine(); channel.ExchangeDeclare(ExchangeName, "topic"); channel.QueueDeclare(CardPaymentQueueName, true, false, false, null); channel.QueueBind(CardPaymentQueueName, ExchangeName, "payment.cardpayment"); channel.BasicQos(0, 10, false); Subscription subscription = new Subscription(channel, CardPaymentQueueName, false); while (true) { BasicDeliverEventArgs deliveryArguments = subscription.Next(); var message = (CardPayment)deliveryArguments.Body.DeSerialize(typeof(CardPayment)); var routingKey = deliveryArguments.RoutingKey; Console.WriteLine("--- Payment - Routing Key <{0}> : {1} : {2}", routingKey, message.CardNumber, message.Amount); subscription.Ack(deliveryArguments); } } } }
private IMessage Receive (IModel model, int timeout, bool doAck) { string finalName = model.QueueDeclare (QRef.Queue, false); using (Subscription sub = new Subscription (model, finalName)) { BasicDeliverEventArgs result; if (sub.Next (timeout, out result)) { IMessage m = helper.ReadMessage (QRef, result); if (doAck) sub.Ack (result); return m; } else { throw new MonoMessagingException ("No Message Available"); } } }
public ICommand Publish(ICommand command, PublicationAddress receiver, TimeSpan? timeout = null) { if (!timeout.HasValue) timeout = TimeSpan.MaxValue; var props = this.Channel.CreateBasicProperties(); //props.AppId; //props.ClusterId; //props.CorrelationId; props.DeliveryMode = Constants.Persistent; //props.Expiration; //props.Headers; //props.MessageId; //props.Priority; //props.ProtocolClassId; //props.ProtocolClassName; //props.ReplyTo; props.ReplyToAddress = new PublicationAddress(this.CmdExchange.ExchangeType, this.CmdExchange.Name, this.PrivateQueue.Name); //props.Timestamp; //props.UserId; var reqBytes = CommandSerializer.Serialize(command); props.ContentEncoding = CommandSerializer.ContentEncoding; props.ContentType = CommandSerializer.ContentType; props.Type = command.GetType().FullName; // at this point, we're ready to send // set up to receive the response before the send occurs // so there's no chance it'll be missed ICommand reply = null; using (CancellationTokenSource cts = new CancellationTokenSource()) { var ct = cts.Token; Task replyTask = null; if (command.CorrelationId.HasValue) { props.CorrelationId = command.CorrelationId.ToString(); replyTask = Task.Run(() => { var autoAck = false; using (var subscription = new Subscription(this.Channel, this.PrivateQueue.Name, autoAck)) { var subscriptionTimeout = TimeSpan.FromMilliseconds(100d).Milliseconds; while (!ct.IsCancellationRequested) { BasicDeliverEventArgs eventArgs = null; subscription.Next(subscriptionTimeout, out eventArgs); if (eventArgs != null && !ct.IsCancellationRequested) { reply = CommandDeserializer.Deserialize(eventArgs.Body) as ICommand; if (reply != null && reply.CorrelationId == command.CorrelationId) { subscription.Ack(eventArgs); break; } else subscription.Model.BasicNack(eventArgs.DeliveryTag, false, true); } } } }); } // now the receiver is set up, publish the command this.Channel.BasicPublish(receiver, props, reqBytes); //Console.WriteLine("{0} Command sent ({1})", command.GetType().Name, command.CorrelationId); if (timeout < TimeSpan.MaxValue) cts.CancelAfter(timeout.Value); replyTask.Wait(); return reply; } }
private IMessage ReceiveWithMatcher (QueueReference qRef, int timeout, IsMatch matcher, bool ack) { IModel _model = Model; string finalName = _model.QueueDeclare (qRef.Queue, false); using (Subscription sub = new Subscription (_model, finalName)) { BasicDeliverEventArgs result; while (sub.Next (timeout, out result)) { if (matcher (result)) { IMessage m = helper.ReadMessage (qRef, result); if (ack) sub.Ack (result); return m; } } throw new MessageUnavailableException ("Message not available"); } }
private void TestSubscriptionAction(SubscriptionAction action) { Model.BasicQos(0, 1, false); string q = Model.QueueDeclare(); Subscription sub = new Subscription(Model, q, false); Model.BasicPublish("", q, null, enc.GetBytes("a message")); BasicDeliverEventArgs res = sub.Next(); Assert.IsNotNull(res); action(sub); QueueDeclareOk ok = Model.QueueDeclarePassive(q); Assert.AreEqual(0, ok.MessageCount); }
public void ReceiveTopicMessageReceiverTwo(IModel model) { model.BasicQos(0, 1, false); Subscription subscription = new Subscription(model, _topicsQueueTwo, false); while (true) { BasicDeliverEventArgs deliveryArguments = subscription.Next(); String message = Encoding.UTF8.GetString(deliveryArguments.Body); Console.WriteLine("Message from queue: {0}", message); subscription.Ack(deliveryArguments); } }
private void TestSubscriptionAction(Action<Subscription> action) { Model.BasicQos(0, 1, false); string queueDeclare = Model.QueueDeclare(); var subscription = new Subscription(Model, queueDeclare, false); Model.BasicPublish("", queueDeclare, null, encoding.GetBytes("a message")); BasicDeliverEventArgs res = subscription.Next(); Assert.IsNotNull(res); action(subscription); QueueDeclareOk ok = Model.QueueDeclarePassive(queueDeclare); Assert.AreEqual(0, ok.MessageCount); }
private IMessage Receive (IModel model, int timeout, bool doAck, IsMatch matcher) { string finalName = model.QueueDeclare (QRef.Queue, false); using (Subscription sub = new Subscription (model, finalName)) { BasicDeliverEventArgs result; while (sub.Next (timeout, out result)) { if (matcher (result)) { IMessage m = helper.ReadMessage (QRef, result); if (doAck) sub.Ack (result); return m; } } throw new MessageUnavailableException ("Message not available"); } }
private void QueChannel(CommandBus bus) { using (IModel model = conn.CreateModel()) { var subscription = new Subscription(model, "queue", false); while (true) { BasicDeliverEventArgs basicDeliveryEventArgs = subscription.Next(); var @event = StreamExtension.Deserialize<Vaccine.Events.DomainEvent>(basicDeliveryEventArgs.Body); //Encoding.UTF8.GetString(basicDeliveryEventArgs.Body); Console.WriteLine(@event.GetType()); bus.Publish(@event); subscription.Ack(basicDeliveryEventArgs); } } }
protected void Page_Load(object sender, EventArgs e) { try { var connectionFactory = new ConnectionFactory(); connectionFactory.HostName = ConfigurationManager.AppSettings["hostname"]; connectionFactory.UserName = ConfigurationManager.AppSettings["username"]; connectionFactory.Password = ConfigurationManager.AppSettings["password"]; connectionFactory.Port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]); connectionFactory.VirtualHost = ConfigurationManager.AppSettings["vhost"]; connectionFactory.Protocol = Protocols.FromEnvironment(); //Response.Write(connectionFactory.HostName + " " + connectionFactory.UserName + " " + // connectionFactory.Port.ToString() + " " + connectionFactory.Password); string message = "Hello!!"; //send message to queue using (IConnection connection = connectionFactory.CreateConnection()) { using (IModel model = connection.CreateModel()) { model.ExchangeDeclare("MyExchange", ExchangeType.Fanout, true); model.QueueDeclare("MyQueue", true, false, false, new Dictionary<string, object>()); model.QueueBind("MyQueue", "MyExchange", "", new Dictionary<string, object>()); IBasicProperties basicProperties = model.CreateBasicProperties(); model.BasicPublish("MyExchange", "", false, false, basicProperties, Encoding.UTF8.GetBytes(message)); } } //consume message from queue using (IConnection connection = connectionFactory.CreateConnection()) { using (IModel model = connection.CreateModel()) { var subscription = new Subscription(model, "MyQueue", false); while (true) { BasicDeliverEventArgs basicDeliveryEventArgs = subscription.Next(); string messageContent = Encoding.UTF8.GetString(basicDeliveryEventArgs.Body); //Response.Write(messageContent); subscription.Ack(basicDeliveryEventArgs); if (messageContent == message) { break; } } } } Response.Write("OK"); } catch (Exception ex) { Response.StatusCode = 500; if (ex.InnerException != null) Response.Write(ex.InnerException.Message); Response.Write(ex.Message + Environment.NewLine + ex.StackTrace); } }
static void Main(string[] args) { try { ConnectionFactory cf = new ConnectionFactory(); cf.Uri = "amqps://<user>:<pass>@<server>:5671/"; cf.Ssl.CertPath = "C:\\keycert.p12"; cf.Ssl.CertPassphrase = "<ClientCertPass>"; cf.Ssl.Enabled = true; using (IConnection conn = cf.CreateConnection()) { Console.WriteLine("Connection established"); using (IModel ch = conn.CreateModel()) { ch.BasicQos(0, 1, false); // noAck Subscription sub = new Subscription(ch, "QueueName", true); // last param MUST BE true while (true) { BasicDeliverEventArgs e = sub.Next(); byte[] body = e.Body; Console.WriteLine(Encoding.UTF8.GetString(body)); } } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }