protected void RunTestDurableConsumer(AcknowledgementMode ackMode) { SendDurableMessage(); using (IConnection connection = CreateConnection(TEST_CLIENT_ID)) { connection.Start(); using (ISession session = connection.CreateSession(AcknowledgementMode.Transactional)) { ITopic topic = SessionUtil.GetTopic(session, DURABLE_TOPIC); using (IMessageConsumer consumer = session.CreateDurableConsumer(topic, CONSUMER_ID, DURABLE_SELECTOR, false)) { IMessage msg = consumer.Receive(receiveTimeout); Assert.IsNotNull(msg, "Did not receive first durable message."); msg.Acknowledge(); SendDurableMessage(); msg = consumer.Receive(receiveTimeout); Assert.IsNotNull(msg, "Did not receive second durable message."); msg.Acknowledge(); if (AcknowledgementMode.Transactional == ackMode) { session.Commit(); } } } } }
public void TestAckedMessageAreConsumed() { ISession session = connection.CreateSession(AcknowledgementMode.IndividualAcknowledge); ITemporaryQueue queue = session.CreateTemporaryQueue(); IMessageProducer producer = session.CreateProducer(queue); producer.Send(session.CreateTextMessage("Hello")); // Consume the message... IMessageConsumer consumer = session.CreateConsumer(queue); IMessage msg = consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNotNull(msg); msg.Acknowledge(); // Reset the session. session.Close(); session = connection.CreateSession(AcknowledgementMode.IndividualAcknowledge); // Attempt to Consume the message... consumer = session.CreateConsumer(queue); msg = consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNull(msg); session.Close(); }
public void OnMessage(IMessage message) { object data = CreateDataObject(message); bool isPermKeyOk = false; //Israel 11/20/2015 -- Added support for permission keys. if (message.NMSType.ToUpper() == "SUMMARY") { SummaryData summaryData = data as SummaryData; isPermKeyOk = (String.IsNullOrEmpty(summaryData.PermissionKey)) || (v_PermKeyList.IndexOf(summaryData.PermissionKey) > -1); if (isPermKeyOk || v_IsSuperUser) { callback.Invoke(this, data); } } //Israel 12/16/2015 -- Message publisher was escaping the : character-- this removes it. else if (message.NMSType.ToUpper() == "CONFIRM") { TradeRqmtConfirm confirmData = data as TradeRqmtConfirm; if (!String.IsNullOrEmpty(confirmData.XmitAddr)) { confirmData.XmitAddr = confirmData.XmitAddr.Replace(@"\", ""); } callback.Invoke(this, data); } else { callback.Invoke(this, data); } message.Acknowledge(); //string testMessage = DateTime.Now.ToShortDateString() + ":" + DateTime.Now.ToLongTimeString() + ": " + message.ToString(); //File.AppendAllText(@"_MessageDump.txt", testMessage + Environment.NewLine); }
public void TestClientAcknowledgeMessages() { using (TestAmqpPeer testAmqpPeer = new TestAmqpPeer(Address, User, Password)) { testAmqpPeer.Open(); int msgCount = 3; for (int i = 0; i < msgCount; i++) { testAmqpPeer.SendMessage("myQueue", "test" + i); } IConnection connection = EstablishConnection(); connection.Start(); ISession session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); IQueue queue = session.GetQueue("myQueue"); IMessageConsumer consumer = session.CreateConsumer(queue); IMessage lastReceivedMessage = null; for (int i = 0; i < msgCount; i++) { lastReceivedMessage = consumer.Receive(); Assert.NotNull(lastReceivedMessage, "Message " + i + " was not received"); } lastReceivedMessage.Acknowledge(); Assert.That(() => testAmqpPeer.AcceptedMessages.Count(), Is.EqualTo(3).After(200, 50)); } }
/// <summary> /// receive message only and non-blocking queue /// </summary> /// <param name="consumer"></param> /// <returns></returns> public String ConvertMessageObjectToString(IMessage msg) { String msgStr = null; if (msg != null) { if (msg is ITextMessage) { msgStr = ((ITextMessage)msg).Text; /// NOTE: there are some null-terminated characters from ES and CCS, so need to convert to whitespaces; otherwise, the message is truncated //msgStr = ((ITextMessage)msg).Text.Replace("\0", " "); //byte[] bytes = Encoding.UTF8.GetBytes(((ITextMessage)msg).Text); //msgStr = "text <" + Encoding.UTF8.GetString(bytes) + ">"; //msgStr = msg.GetIntProperty(XMSC.JMS_IBM_CHARACTER_SET) + " " + msg.GetIntProperty(XMSC.JMS_IBM_ENCODING) + " " + ((ITextMessage)msg).Text; } else if (msg is IBytesMessage) { int num = (int)((IBytesMessage)msg).BodyLength; byte[] bytes = new byte[num]; ((IBytesMessage)msg).ReadBytes(bytes); msgStr = Encoding.UTF8.GetString(bytes); } msg.Acknowledge(); // msg.ClearBody(); } return(msgStr); }
public void TestAcknowledgeFailsAfterSessionIsClosed() { using (TestAmqpPeer testAmqpPeer = new TestAmqpPeer(Address, User, Password)) { testAmqpPeer.Open(); testAmqpPeer.SendMessage("myQueue", "test"); IConnection connection = EstablishConnection(); connection.Start(); ISession session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); IQueue queue = session.GetQueue("myQueue"); IMessageConsumer consumer = session.CreateConsumer(queue); IMessage receivedMessage = consumer.Receive(); Assert.NotNull(receivedMessage, "Message was not received"); session.Close(); try { receivedMessage.Acknowledge(); Assert.Fail("Should not be able to acknowledge the message after session closed"); } catch (NMSException) { } } }
private void Acknowledge(IMessage message) { if (_mode != Apache.NMS.AcknowledgementMode.AutoAcknowledge) { message.Acknowledge(); } }
public void TestLastMessageAcked() { using (IConnection connection = CreateConnection(TEST_CLIENT_ID)) { connection.Start(); ISession session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); IQueue queue = session.GetQueue(Guid.NewGuid().ToString()); IMessageProducer producer = session.CreateProducer(queue); producer.Send(session.CreateTextMessage("Hello")); producer.Send(session.CreateTextMessage("Hello2")); producer.Send(session.CreateTextMessage("Hello3")); // Consume the message... IMessageConsumer consumer = session.CreateConsumer(queue); IMessage msg = consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNotNull(msg); msg = consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNotNull(msg); msg = consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNotNull(msg); msg.Acknowledge(); // Reset the session. session.Close(); session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); // Attempt to Consume the message... consumer = session.CreateConsumer(queue); msg = consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNull(msg); session.Close(); } }
//[Test] public virtual void TestUnAckedMessageAreNotConsumedOnSessionClose(string testDestRef) { using (IConnection connection = CreateConnection()) { connection.Start(); ISession session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); IDestination destination = GetClearDestinationByNodeReference(session, testDestRef); IMessageProducer producer = session.CreateProducer(destination); producer.Send(session.CreateTextMessage("Hello")); // Consume the message... IMessageConsumer consumer = session.CreateConsumer(destination); IMessage msg = consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNotNull(msg); // Don't ack the message. // Reset the session. This should cause the unacknowledged message to be re-delivered. session.Close(); session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); // Attempt to Consume the message... consumer = session.CreateConsumer(destination); msg = consumer.Receive(TimeSpan.FromMilliseconds(2000)); Assert.IsNotNull(msg); msg.Acknowledge(); session.Close(); } }
public void TestUnAckedMessageAreNotConsumedOnSessionClose() { using (IConnection connection = CreateConnection(TEST_CLIENT_ID)) { connection.Start(); ISession session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); IQueue queue = session.GetQueue(Guid.NewGuid().ToString()); IMessageProducer producer = session.CreateProducer(queue); producer.Send(session.CreateTextMessage("Hello")); // Consume the message... IMessageConsumer consumer = session.CreateConsumer(queue); IMessage msg = consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNotNull(msg); // Don't ack the message. // Reset the session. This should cause the unacknowledged message to be re-delivered. session.Close(); session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); // Attempt to Consume the message... consumer = session.CreateConsumer(queue); msg = consumer.Receive(TimeSpan.FromMilliseconds(2000)); Assert.IsNotNull(msg); msg.Acknowledge(); session.Close(); } }
public void TestUnAckedMessageAreNotConsumedOnSessionClose() { ISession session = connection.CreateSession(AcknowledgementMode.IndividualAcknowledge); ITemporaryQueue queue = session.CreateTemporaryQueue(); IMessageProducer producer = session.CreateProducer(queue); producer.Send(session.CreateTextMessage("Hello")); // Consume the message... IMessageConsumer consumer = session.CreateConsumer(queue); IMessage msg = consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNotNull(msg); // Don't ack the message. // Reset the session. This should cause the unacknowledged message to be re-delivered. session.Close(); session = connection.CreateSession(AcknowledgementMode.IndividualAcknowledge); // Attempt to Consume the message... consumer = session.CreateConsumer(queue); msg = consumer.Receive(TimeSpan.FromMilliseconds(2000)); Assert.IsNotNull(msg); msg.Acknowledge(); session.Close(); }
async void HandleMessage(IMessage message) { LogContext.Current = _context.LogContext; if (IsStopping) { await WaitAndAbandonMessage(message).ConfigureAwait(false); return; } var delivery = _tracker.BeginDelivery(); var context = new ActiveMqReceiveContext(_inputAddress, message, _context, _receiveSettings, _session, _session.ConnectionContext); var activity = LogContext.IfEnabled(OperationName.Transport.Receive)?.StartActivity(); activity.AddReceiveContextHeaders(context); try { if (!_pending.TryAdd(message.NMSMessageId, context)) { LogContext.Warning?.Log("Duplicate message: {MessageId}", message.NMSMessageId); } if (_context.ReceiveObservers.Count > 0) { await _context.ReceiveObservers.PreReceive(context).ConfigureAwait(false); } await _context.ReceivePipe.Send(context).ConfigureAwait(false); await context.ReceiveCompleted.ConfigureAwait(false); message.Acknowledge(); if (_context.ReceiveObservers.Count > 0) { await _context.ReceiveObservers.PostReceive(context).ConfigureAwait(false); } } catch (Exception ex) { if (_context.ReceiveObservers.Count > 0) { await _context.ReceiveObservers.ReceiveFault(context, ex).ConfigureAwait(false); } } finally { activity?.Stop(); delivery.Dispose(); _pending.TryRemove(message.NMSMessageId, out _); context.Dispose(); } }
public void TestAsyncUnAckedMessageAreNotConsumedOnSessionClose() { using (IConnection connection = CreateConnection(TEST_CLIENT_ID)) { connection.Start(); // don't aknowledge message on onMessage() call dontAck = true; ISession session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); IQueue queue = session.GetQueue("Guid.NewGuid().ToString()"); IMessageProducer producer = session.CreateProducer(queue); producer.Send(session.CreateTextMessage("Hello")); // Consume the message... IMessageConsumer consumer = session.CreateConsumer(queue); consumer.Listener += new MessageListener(OnMessage); // Don't ack the message. // Reset the session. This should cause the Unacked message to be // redelivered. session.Close(); Thread.Sleep(5000); session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); // Attempt to Consume the message... consumer = session.CreateConsumer(queue); IMessage msg = consumer.Receive(TimeSpan.FromMilliseconds(2000)); Assert.IsNotNull(msg); msg.Acknowledge(); session.Close(); } }
public void OnMessage(IMessage message) { object data = CreateDataObject(message); bool isPermKeyOk = false; //Israel 11/20/2015 -- Added support for permission keys. if (message.NMSType.ToUpper() == "SUMMARY") { SummaryData summaryData = data as SummaryData; isPermKeyOk = (String.IsNullOrEmpty(summaryData.PermissionKey)) || (v_PermKeyList.IndexOf(summaryData.PermissionKey) > -1); if (isPermKeyOk || v_IsSuperUser) callback.Invoke(this, data); } //Israel 12/16/2015 -- Message publisher was escaping the : character-- this removes it. else if (message.NMSType.ToUpper() == "CONFIRM") { TradeRqmtConfirm confirmData = data as TradeRqmtConfirm; if (!String.IsNullOrEmpty(confirmData.XmitAddr)) confirmData.XmitAddr = confirmData.XmitAddr.Replace(@"\", ""); callback.Invoke(this, data); } else { callback.Invoke(this, data); } message.Acknowledge(); //string testMessage = DateTime.Now.ToShortDateString() + ":" + DateTime.Now.ToLongTimeString() + ": " + message.ToString(); //File.AppendAllText(@"_MessageDump.txt", testMessage + Environment.NewLine); }
protected void HandleMessage(IMessage receivedMsg) { ITextMessage message = receivedMsg as ITextMessage; if (message == null) { Logger.Warning(string.Format("received JMS message with id {0} which is not a text message", receivedMsg.NMSMessageId)); receivedMsg.Acknowledge(); return; } Logger.Debug(string.Format("received text message with id {0} and text {1}", message.NMSMessageId, message.Text)); try { ICacheEvent cacheEvent = CacheEventSerializer.Deserialize(message.Text); foreach (IObserver <ICacheEvent> observer in observers) { observer.OnNext(cacheEvent); } } catch (Exception e) { Logger.Error("error in invalidation transaction: {0}", e.ToString()); foreach (IObserver <ICacheEvent> observer in observers) { observer.OnError(e); } } finally { message.Acknowledge(); Logger.Debug(string.Format("acknowledged received message with id {0}", message.NMSMessageId)); } }
/// <summary> /// Receives all of the test messages. /// </summary> /// /// <param name="message">The newly arrived test message.</param> public void OnMessage(IMessage message) { try { if (_acknowledgeMode == AcknowledgeMode.ClientAcknowledge) { message.Acknowledge(); } messagesReceived++; _log.Debug("messagesReceived = " + messagesReceived); // Check if all of the messages in the test have been received, in which case notify the message producer that the test has // succesfully completed. if (messagesReceived == NUM_MESSAGES + _extraMessage) { lock (testComplete) { failedOver = true; Monitor.Pulse(testComplete); } } } catch (QpidException e) { _log.Fatal("Exception received. About to stop.", e); Stop(); } }
public void TestLastMessageAcked() { using (IConnection connection = CreateConnection()) { connection.Start(); ISession session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); IDestination destination = CreateDestination(session, DestinationType.Queue); IMessageProducer producer = session.CreateProducer(destination); producer.Send(session.CreateTextMessage("Hello")); producer.Send(session.CreateTextMessage("Hello2")); producer.Send(session.CreateTextMessage("Hello3")); // Consume the message... IMessageConsumer consumer = session.CreateConsumer(destination); IMessage msg = consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNotNull(msg); msg = consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNotNull(msg); msg = consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNotNull(msg); msg.Acknowledge(); // Reset the session. session.Close(); session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); // Attempt to Consume the message... consumer = session.CreateConsumer(destination); msg = consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNull(msg); session.Close(); } }
public void TestAcknowledgeFailsAfterSessionIsClosed() { using (TestAmqpPeer testPeer = new TestAmqpPeer()) { IConnection connection = EstablishConnection(testPeer); connection.Start(); testPeer.ExpectBegin(); ISession session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); IQueue queue = session.GetQueue("myQueue"); testPeer.ExpectReceiverAttach(); testPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithNullContent(), count: 1); testPeer.ExpectEnd(); IMessageConsumer consumer = session.CreateConsumer(queue); IMessage receivedMessage = consumer.Receive(TimeSpan.FromSeconds(6)); Assert.NotNull(receivedMessage, "Message was not received"); session.Close(); Assert.Catch <NMSException>(() => receivedMessage.Acknowledge(), "Should not be able to acknowledge the message after session closed"); testPeer.ExpectClose(); connection.Close(); testPeer.WaitForAllMatchersToComplete(3000); } }
private void MessagesListener(IMessage message) { ITextMessage textMessage = message as ITextMessage; Console.WriteLine(textMessage.Text); message.Acknowledge(); }
public void TestCloseDurableSubscriberWithUnackedAndUnconsumedPrefetchedMessages() { using (TestAmqpPeer testPeer = new TestAmqpPeer()) { IConnection connection = EstablishConnection(testPeer); connection.Start(); testPeer.ExpectBegin(); ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge); string topicName = "myTopic"; string subscriptionName = "mySubscription"; ITopic topic = session.GetTopic(topicName); int messageCount = 5; // Create a consumer and fill the prefetch with some messages, // which we will consume some of but ack none of. testPeer.ExpectDurableSubscriberAttach(topicName, subscriptionName); testPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithContent(), count: messageCount); IMessageConsumer durableConsumer = session.CreateDurableConsumer(topic, subscriptionName, null, false); int consumeCount = 2; IMessage receivedMessage = null; for (int i = 1; i <= consumeCount; i++) { receivedMessage = durableConsumer.Receive(); Assert.NotNull(receivedMessage); Assert.IsInstanceOf <NmsTextMessage>(receivedMessage); } // Expect the messages that were not delivered to be released. for (int i = 1; i <= consumeCount; i++) { testPeer.ExpectDispositionThatIsAcceptedAndSettled(); } receivedMessage.Acknowledge(); testPeer.ExpectDetach(expectClosed: false, sendResponse: true, replyClosed: false); for (int i = consumeCount + 1; i <= messageCount; i++) { testPeer.ExpectDispositionThatIsReleasedAndSettled(); } testPeer.ExpectEnd(); durableConsumer.Close(); session.Close(); testPeer.ExpectClose(); connection.Close(); testPeer.WaitForAllMatchersToComplete(3000); } }
private void MessageListenerB(IMessage message) { message.Acknowledge(); ITextMessage messageB = message as ITextMessage; string msgText = "Message #" + receivedB; Assert.AreEqual(msgText, messageB.Text, "Message text B does not match."); Tracer.Info("Received Listener B: " + msgText); receivedB++; }
private void OnMessageListener(IMessage message) { counter++; if (this.counter <= 4) { session.Rollback(); } else { message.Acknowledge(); session.Commit(); } }
private void OnMessageListener(IMessage message) { counter++; if(this.counter <= 4) { session.Rollback(); } else { message.Acknowledge(); session.Commit(); } }
//[Test] public virtual void TestReceiveNoWait( string testDestRef, //[Values(AcknowledgementMode.AutoAcknowledge, AcknowledgementMode.ClientAcknowledge, // AcknowledgementMode.DupsOkAcknowledge, AcknowledgementMode.Transactional)] AcknowledgementMode ackMode, //[Values(MsgDeliveryMode.NonPersistent, MsgDeliveryMode.Persistent)] MsgDeliveryMode deliveryMode) { const int RETRIES = 20; using (IConnection connection = CreateConnection()) { connection.Start(); using (ISession session = connection.CreateSession(ackMode)) { IDestination destination = GetClearDestinationByNodeReference(session, testDestRef); using (IMessageProducer producer = session.CreateProducer(destination)) { producer.DeliveryMode = deliveryMode; ITextMessage message = session.CreateTextMessage("TEST"); producer.Send(message); if (AcknowledgementMode.Transactional == ackMode) { session.Commit(); } } using (IMessageConsumer consumer = session.CreateConsumer(destination)) { IMessage message = null; for (int i = 0; i < RETRIES && message == null; ++i) { message = consumer.ReceiveNoWait(); Thread.Sleep(100); } Assert.IsNotNull(message); message.Acknowledge(); if (AcknowledgementMode.Transactional == ackMode) { session.Commit(); } } } } }
public void OnMessage(IMessage message) { Assert.IsNotNull(message); if(!dontAck) { try { message.Acknowledge(); } catch(Exception) { } } }
public void OnMessage(IMessage message) { Assert.IsNotNull(message); if (!dontAck) { try { message.Acknowledge(); } catch (Exception) { } } }
/// <summary> /// Perform a commit or message acknowledgement, as appropriate /// </summary> /// <param name="session">The session to commit.</param> /// <param name="message">The message to acknowledge.</param> /// <exception cref="NMSException">In case of commit failure</exception> protected virtual void CommitIfNecessary(ISession session, IMessage message) { // Commit session or acknowledge message if (session.Transacted) { // Commit necessary - but avoid commit call is Session transaction is externally coordinated. if (IsSessionLocallyTransacted(session)) { NmsUtils.CommitIfNecessary(session); } } else if (IsClientAcknowledge(session)) { message.Acknowledge(); } }
public void TestClientAcknowledgeMessagesAsync() { using (TestAmqpPeer testPeer = new TestAmqpPeer()) { int msgCount = 3; IConnection connection = EstablishConnection(testPeer); connection.Start(); testPeer.ExpectBegin(); ISession session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); IQueue queue = session.GetQueue("myQueue"); testPeer.ExpectReceiverAttach(); testPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithNullContent(), count: msgCount); IMessageConsumer consumer = session.CreateConsumer(queue); CountdownEvent latch = new CountdownEvent(3); IMessage lastReceivedMessage = null; consumer.Listener += message => { lastReceivedMessage = message; latch.Signal(); }; Assert.True(latch.Wait(2000)); for (int i = 0; i < msgCount; i++) { testPeer.ExpectDispositionThatIsAcceptedAndSettled(); } lastReceivedMessage.Acknowledge(); testPeer.WaitForAllMatchersToComplete(2000); testPeer.ExpectClose(); connection.Close(); testPeer.WaitForAllMatchersToComplete(2000); } }
private static void Message_Listener(IMessage message) { try { Console.WriteLine("Add Message"); IObjectMessage objectMessage = message as IObjectMessage; if (objectMessage.Body != null) { var smsJson = (string)objectMessage.Body; if (!String.IsNullOrEmpty(smsJson)) { var sUserName = ConfigHelper.GetConfigValueByKey("smsUserName"); var sPwd = ConfigHelper.GetConfigValueByKey("smsPwd"); Console.WriteLine(string.Format("Message received: Body = {0}", smsJson)); var sms = new JavaScriptSerializer().Deserialize <SmsSenderModel>(smsJson); var url = String.Format( "http://smsc.ru/sys/send.php?login={0}&psw={1}&phones={2}&mes={3}&sender={4}&charset=utf-8&translit={5}", sUserName, sPwd, sms.Phone, sms.Message, sms.Sender, ConfigHelper.GetConfigValueByKey("Translit")); var request = WebRequest.Create(url); request.Credentials = CredentialCache.DefaultCredentials; var response = (HttpWebResponse)request.GetResponse(); response.Close(); Console.WriteLine(url); message.Acknowledge(); Console.WriteLine(smsJson); StreamWriter sw = new StreamWriter("out.txt", true); sw.WriteLine("Message==={0}==={1}", DateTime.Now.ToString(), smsJson); sw.Close(); } Thread.Sleep(5000); } } catch (Exception e) { StreamWriter sw = new StreamWriter("error.txt", true); sw.WriteLine("Error==={0}==={1}", DateTime.Now.ToString(), e.ToString()); sw.Close(); } }
public override void Listen() { string queueName = "TextQueue"; string brokerUri = $"activemq:tcp://localhost:61616"; // Default port NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri); using (Apache.NMS.IConnection connection = factory.CreateConnection()) { connection.Start(); using (ISession session = connection.CreateSession(AcknowledgementMode.IndividualAcknowledge)) using (IDestination dest = session.GetQueue(queueName)) using (IMessageConsumer consumer = session.CreateConsumer(dest)) { IMessage msg = consumer.Receive(); try { if ((msg is ITextMessage) == false) { throw new Exception("Unexpected message type: " + msg.GetType().Name); } ITextMessage txtMsg = msg as ITextMessage; string jsonMessage = txtMsg.Text; var messageContext = DesypherMessageType(jsonMessage); Interpret(messageContext); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { msg.Acknowledge(); } } } }
public void TestClientAcknowledgeMessages() { using (TestAmqpPeer testPeer = new TestAmqpPeer()) { int msgCount = 3; IConnection connection = EstablishConnection(testPeer); connection.Start(); testPeer.ExpectBegin(); ISession session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); IQueue queue = session.GetQueue("myQueue"); testPeer.ExpectReceiverAttach(); testPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithNullContent(), count: msgCount); IMessageConsumer consumer = session.CreateConsumer(queue); IMessage lastReceivedMessage = null; for (int i = 0; i < msgCount; i++) { lastReceivedMessage = consumer.Receive(); Assert.NotNull(lastReceivedMessage, "Message " + i + " was not received"); } for (int i = 0; i < msgCount; i++) { testPeer.ExpectDispositionThatIsAcceptedAndSettled(); } lastReceivedMessage.Acknowledge(); testPeer.WaitForAllMatchersToComplete(2000); testPeer.ExpectClose(); connection.Close(); testPeer.WaitForAllMatchersToComplete(2000); } }
//[Test] public virtual void TestReceiveRollbackNonTransaction( //[Values(AcknowledgementMode.AutoAcknowledge, AcknowledgementMode.ClientAcknowledge)] AcknowledgementMode ackMode, //[Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)] MsgDeliveryMode deliveryMode, string testQueueRef) { using (IConnection connection = CreateConnection(GetTestClientId())) { connection.Start(); using (ISession session = connection.CreateSession(ackMode)) { IDestination destination = GetClearDestination(session, DestinationType.Queue, testQueueRef); using (IMessageConsumer consumer = session.CreateConsumer(destination)) using (IMessageProducer producer = session.CreateProducer(destination)) { producer.DeliveryMode = deliveryMode; ITextMessage firstMsgSend = session.CreateTextMessage("ReceiveCommitNonTransaction Message"); producer.Send(firstMsgSend); // Receive the messages IMessage message = consumer.Receive(receiveTimeout); AssertTextMessageEqual(firstMsgSend, message, "First message does not match."); if (AcknowledgementMode.ClientAcknowledge == ackMode) { message.Acknowledge(); } try { session.Rollback(); Assert.Fail("Should have thrown an InvalidOperationException."); } catch (InvalidOperationException) { } } } } }
public void TestCloseDurableSubscriberWithUnackedAnUnconsumedPrefetchedMessages() { using (TestAmqpPeer testAmqpPeer = new TestAmqpPeer(Address, User, Password)) { string topicName = "myTopic"; testAmqpPeer.Open(); IConnection connection = EstablishConnection(); ISession session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge); string subscriptionName = "mySubscription"; ITopic topic = session.GetTopic(topicName); // Create a consumer and fill the prefetch with some messages, // which we will consume some of but ack none of. for (int i = 0; i < 5; i++) { testAmqpPeer.SendMessage(topicName, "test" + i); } IMessageConsumer durableConsumer = session.CreateDurableConsumer(topic, subscriptionName, null, false); int consumeCount = 2; IMessage receivedMessage = null; for (int i = 1; i <= consumeCount; i++) { receivedMessage = durableConsumer.Receive(); Assert.NotNull(receivedMessage); Assert.IsInstanceOf <NmsTextMessage>(receivedMessage); } Assert.NotNull(receivedMessage); receivedMessage.Acknowledge(); durableConsumer.Close(); // Expect the messages that were not delivered to be released. Assert.AreEqual(2, testAmqpPeer.ReleasedMessages.Count()); } }
public void MessageAccepted(IMessage message) { message.Acknowledge(); }
protected void OnInvalidate(IMessage receivedMsg) { IObjectMessage m2 = receivedMsg as IObjectMessage; Debug.WriteLine("message has the following raw content:"); // Debug.WriteLine(m2.) try { object obj = m2.Body; } catch (Exception e) { Debug.WriteLine("caught exception while accessing message body: " + e.Message); } object obj2 = m2.ToObject(); var msg = receivedMsg as IBytesMessage; var result = msg != null ? new UTF8Encoding().GetString(msg.Content) : "bytes message is null"; ITextMessage message = receivedMsg as ITextMessage; if (message == null) { Logger.Debug(string.Format("message with id {0} is not a text message", receivedMsg.NMSMessageId)); Debug.WriteLine(string.Format("message with id {0} is not a text message", receivedMsg.NMSMessageId)); receivedMsg.Acknowledge(); return; } Logger.Debug(string.Format("received text message with id {0} and text {1}", message.NMSMessageId, message.Text)); Debug.WriteLine(string.Format("received text message with id {0} and text {1}", message.NMSMessageId, message.Text)); try { var invalidationInformation = GetInvalidationInformation(message); foreach (string dcpUri in invalidationInformation.InvalidationDcps) { foreach (ICacheAgent cacheAgent in CacheAgents) { Logger.Debug(string.Format("telling cache agent {0} to remove DCP with uri {1}", cacheAgent.GetType().Name, dcpUri)); //cacheAgent.Remove(dcpUri) } } foreach (InvalidationUrl url in invalidationInformation.InvalidationUrls) { foreach (ICacheAgent cacheAgent in CacheAgents) { Logger.Debug(string.Format("telling cache agent {0} to remove page with url {1}", cacheAgent.GetType().Name, url.TcmUri)); //cacheAgent.Remove(url.TcmUri) } } //LoggerService.Debug("<<Received message: finished processing"); } catch (Exception e) { Logger.Error("error in invalidation transaction: {0}", e.ToString()); } finally { message.Acknowledge(); Logger.Debug(string.Format("acknowledged received message with id {0}", message.NMSMessageId)); } }