public void TestCloseDurableTopicSubscriberDetachesWithCloseFalse() { 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); testPeer.ExpectDurableSubscriberAttach(topicName, subscriptionName); testPeer.ExpectLinkFlow(); IMessageConsumer durableConsumer = session.CreateDurableConsumer(topic, subscriptionName, null, false); testPeer.ExpectDetach(expectClosed: false, sendResponse: true, replyClosed: false); durableConsumer.Close(); testPeer.ExpectClose(); connection.Close(); testPeer.WaitForAllMatchersToComplete(1000); } }
public void Dispose() { if (disposed) { return; } sender.Close(); sender.Dispose(); if (receiver != null) { receiver.Close(); receiver.Dispose(); } session.Close(); session.Dispose(); connection.Stop(); connection.Close(); connection.Dispose(); disposed = true; }
public void TestCloseConsumerBeforeCommit() { Connection = CreateAmqpConnection(); Connection.Start(); SendToAmqQueue(2); ISession session = Connection.CreateSession(AcknowledgementMode.Transactional); IQueue queue = session.GetQueue(TestName); IMessageConsumer consumer = session.CreateConsumer(queue); IMessage message = consumer.Receive(TimeSpan.FromSeconds(5)); Assert.NotNull(message); Assert.AreEqual(1, message.Properties.GetInt(MESSAGE_NUMBER)); consumer.Close(); session.Commit(); // Create a new consumer consumer = session.CreateConsumer(queue); message = consumer.Receive(TimeSpan.FromSeconds(5)); Assert.NotNull(message); Assert.AreEqual(2, message.Properties.GetInt(MESSAGE_NUMBER)); session.Commit(); AssertQueueEmpty(TimeSpan.FromMilliseconds(1000)); }
public void TestCantDeleteTemporaryQueueWithConsumers() { using (TestAmqpPeer testPeer = new TestAmqpPeer()) { IConnection connection = EstablishConnection(testPeer); connection.Start(); testPeer.ExpectBegin(); ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge); string dynamicAddress = "myTempQueueAddress"; testPeer.ExpectTempQueueCreationAttach(dynamicAddress); ITemporaryQueue temporaryQueue = session.CreateTemporaryQueue(); testPeer.ExpectReceiverAttach(); testPeer.ExpectLinkFlow(); IMessageConsumer consumer = session.CreateConsumer(temporaryQueue); Assert.Catch <IllegalStateException>(() => temporaryQueue.Delete(), "should not be able to delete temporary queue with active consumers"); testPeer.ExpectDetach(expectClosed: true, sendResponse: true, replyClosed: true); consumer.Close(); // Now it should be allowed testPeer.ExpectDetach(expectClosed: true, sendResponse: true, replyClosed: true); temporaryQueue.Delete(); testPeer.ExpectClose(); connection.Close(); testPeer.WaitForAllMatchersToComplete(2000); } }
private IDisposable subscribe(IDestination destination, Action <IMessage> callback, string messageType) { IDisposable subscription = null; var selectors = new List <string>(); selectors.Add(messageType != null ? "JMSType = '" + messageType + "'" : null); selectors.Add(m_JailedTag != null ? m_JailedSelector : null); selectors.AddRange(m_CustomSelectors.Select(param => param.Key + " = '" + param.Value + "'")); var selectorsArray = selectors.Where(x => x != null).ToArray(); IMessageConsumer consumer = selectorsArray.Length == 0 ? m_Session.CreateConsumer(destination) : m_Session.CreateConsumer(destination, string.Join(" AND ", selectorsArray)); consumer.Message += (sender, args) => callback(args.Message); subscription = Disposable.Create(() => { lock (this) { consumer.Close(); // ReSharper disable AccessToModifiedClosure m_Subscriptions.Remove(subscription); // ReSharper restore AccessToModifiedClosure if (m_Subscriptions.Count == 0) { m_Session.Close(); m_Session = null; } } }); m_Subscriptions.Add(subscription); return(subscription); }
protected static void VerifyBrokerStateNoRecover(int expectedNumberOfMessages) { IConnectionFactory factory = new ConnectionFactory(ReplaceEnvVar(connectionURI)); using (IConnection connection = factory.CreateConnection()) { // check messages are present in the queue using (ISession session = connection.CreateSession()) { IDestination queue = session.GetQueue(testQueueName); using (IMessageConsumer consumer = session.CreateConsumer(queue)) { connection.Start(); IMessage msg; for (int i = 0; i < expectedNumberOfMessages; ++i) { msg = consumer.Receive(TimeSpan.FromMilliseconds(2000)); Assert.IsNotNull(msg, "message is not in the queue !"); } // next message should be empty msg = consumer.Receive(TimeSpan.FromMilliseconds(2000)); Assert.IsNull(msg, "message found but not expected !"); consumer.Close(); } } connection.Close(); } }
public void Subscribe(string topicName) { var connection = _connectionFactory.CreateConnection(); connection.ExceptionListener = IbmMQService.OnException; var session = connection.CreateSession(false, AcknowledgeMode.AutoAcknowledge); IDestination topic = session.CreateTopic(topicName); IMessageConsumer subscriber = session.CreateConsumer(topic); connection.Start(); Console.WriteLine("Waiting for messages...."); while (true) { var textMessage = (ITextMessage)subscriber.Receive(); if (textMessage != null) { Console.WriteLine(textMessage.Text); if (textMessage.Text.Equals("Exit")) { break; } } } connection.Close(); subscriber.Close(); topic.Dispose(); }
public void Listen(int second = 1) { var connection = _connectionFactory.CreateConnection(); connection.ExceptionListener = IbmMQService.OnException; var session = connection.CreateSession(false, AcknowledgeMode.AutoAcknowledge); IDestination topic = session.CreateQueue(_mqConfigModel.QueueName); IMessageConsumer consumer = session.CreateConsumer(topic); connection.Start(); Console.WriteLine("Waiting for messages...."); for (int i = 0; i < second; i++) { var textMessage = (ITextMessage)consumer.Receive(1000); if (textMessage != null) { Console.WriteLine(textMessage.Text); if (textMessage.Text.Equals("Exit")) { break; } } } connection.Close(); consumer.Close(); topic.Dispose(); }
public void TestFallbackToExclusiveConsumer() { IConnection conn = createConnection(true); ISession exclusiveSession = null; ISession fallbackSession = null; ISession senderSession = null; try { exclusiveSession = conn.CreateSession(AcknowledgementMode.AutoAcknowledge); fallbackSession = conn.CreateSession(AcknowledgementMode.AutoAcknowledge); senderSession = conn.CreateSession(AcknowledgementMode.AutoAcknowledge); // This creates the exclusive consumer first which avoids AMQ-1024 // bug. ActiveMQQueue exclusiveQueue = new ActiveMQQueue("TEST.QUEUE4?consumer.exclusive=true"); IMessageConsumer exclusiveConsumer = exclusiveSession.CreateConsumer(exclusiveQueue); ActiveMQQueue fallbackQueue = new ActiveMQQueue("TEST.QUEUE4"); IMessageConsumer fallbackConsumer = fallbackSession.CreateConsumer(fallbackQueue); ActiveMQQueue senderQueue = new ActiveMQQueue("TEST.QUEUE4"); IMessageProducer producer = senderSession.CreateProducer(senderQueue); producer.DeliveryMode = MsgDeliveryMode.NonPersistent; IMessage msg = senderSession.CreateTextMessage("test"); producer.Send(msg); Thread.Sleep(500); // Verify exclusive consumer receives the message. Assert.IsNotNull(exclusiveConsumer.Receive(TimeSpan.FromMilliseconds(1000))); Assert.IsNull(fallbackConsumer.Receive(TimeSpan.FromMilliseconds(1000))); // Close the exclusive consumer to verify the non-exclusive consumer // takes over exclusiveConsumer.Close(); producer.Send(msg); // Verify other non-exclusive consumer receices the message. Assert.IsNotNull(fallbackConsumer.Receive(TimeSpan.FromMilliseconds(1000))); // Create exclusive consumer to determine if it will start receiving // the messages. exclusiveConsumer = exclusiveSession.CreateConsumer(exclusiveQueue); producer.Send(msg); Assert.IsNotNull(exclusiveConsumer.Receive(TimeSpan.FromMilliseconds(1000))); Assert.IsNull(fallbackConsumer.Receive(TimeSpan.FromMilliseconds(1000))); } finally { fallbackSession.Close(); senderSession.Close(); conn.Close(); } }
private void DoRemotelyCloseConsumerWithMessageListenerFiresNMSExceptionListenerTestImpl(Symbol errorType, string errorMessage) { using (TestAmqpPeer testPeer = new TestAmqpPeer()) { ManualResetEvent consumerClosed = new ManualResetEvent(false); ManualResetEvent exceptionListenerFired = new ManualResetEvent(false); testPeer.ExpectSaslAnonymous(); testPeer.ExpectOpen(); testPeer.ExpectBegin(); NmsConnection connection = EstablishAnonymousConnection("failover.maxReconnectAttempts=1", testPeer); connection.ExceptionListener += exception => { exceptionListenerFired.Set(); }; Mock <INmsConnectionListener> connectionListener = new Mock <INmsConnectionListener>(); connectionListener .Setup(listener => listener.OnConsumerClosed(It.IsAny <IMessageConsumer>(), It.IsAny <Exception>())) .Callback(() => { consumerClosed.Set(); }); connection.AddConnectionListener(connectionListener.Object); testPeer.ExpectBegin(); testPeer.ExpectBegin(nextOutgoingId: 2); ISession session1 = connection.CreateSession(AcknowledgementMode.AutoAcknowledge); ISession session2 = connection.CreateSession(AcknowledgementMode.AutoAcknowledge); IQueue queue = session2.GetQueue("myQueue"); // Create a consumer, then remotely end it afterwards. testPeer.ExpectReceiverAttach(); testPeer.ExpectLinkFlow(); testPeer.ExpectEnd(); testPeer.RemotelyDetachLastOpenedLinkOnLastOpenedSession(expectDetachResponse: true, closed: true, errorType: errorType, errorMessage: errorMessage, delayBeforeSend: 10); IMessageConsumer consumer = session2.CreateConsumer(queue); consumer.Listener += message => { }; // Close first session to allow the receiver remote close timing to be deterministic session1.Close(); // Verify the consumer gets marked closed testPeer.WaitForAllMatchersToComplete(1000); Assert.True(consumerClosed.WaitOne(TimeSpan.FromMilliseconds(2000)), "Consumer closed callback didn't trigger"); Assert.True(exceptionListenerFired.WaitOne(TimeSpan.FromMilliseconds(2000)), "NMS Exception listener should have fired with a MessageListener"); // Try closing it explicitly, should effectively no-op in client. // The test peer will throw during close if it sends anything. consumer.Close(); // Shut the connection down testPeer.ExpectClose(); connection.Close(); testPeer.WaitForAllMatchersToComplete(1000); } }
public CaptureDTO Popup(string userId) { var sysUser = _sysUserRepository.GetById(userId.ToInt()); if (sysUser.IsNotNull() && !sysUser.SysChannels.IsNullOrEmpty()) { var sb = new StringBuilder(); sysUser.SysChannels.ToList().ForEach(t => sb.Append($"or channel='{t.Name}' ")); var selector = sb.ToString().TrimStart('o', 'r').TrimEnd(' '); var rtnJson = string.Empty; IConnectionFactory factory = new ConnectionFactory(ConfigPara.MQIdaddress); //Create the connection using (Apache.NMS.IConnection connection = factory.CreateConnection()) { try { connection.ClientId = "SKCustome" + userId; connection.Start(); //Create the Session using (ISession session = connection.CreateSession()) { IMessageConsumer consumer = session.CreateDurableConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("MQMessage"), sysUser.Name, selector, false); var i = 10; while (i > 0) { ITextMessage msg = (ITextMessage)consumer.Receive(new TimeSpan(1000)); if (msg != null) { rtnJson = msg.Text; } i--; } consumer.Close(); } } catch { } finally { connection.Stop(); connection.Close(); } } var capture = rtnJson.ToObject <Capture>(); if (capture.IsNotNull()) { if (capture.CreateTime.AddMinutes(2) > DateTime.Now) { return(capture.ConvertoDto <Capture, CaptureDTO>()); } } } return(default(CaptureDTO)); }
public void TestURI(string connectionURI) { { Uri uri = URISupport.CreateCompatibleUri(NMSTestSupport.ReplaceEnvVar(connectionURI)); NetTxConnectionFactory factory = new NetTxConnectionFactory(uri); Assert.IsNotNull(factory); using (IConnection connection = factory.CreateConnection("", "")) { Assert.IsNotNull(connection); using (ISession session = connection.CreateSession()) { IDestination destination = session.CreateTemporaryTopic(); using (IMessageProducer producer = session.CreateProducer(destination)) { producer.Close(); } using (IMessageConsumer consumer = session.CreateConsumer(destination)) { consumer.Close(); } session.Close(); } connection.Close(); } } { NetTxConnectionFactory factory = new NetTxConnectionFactory(NMSTestSupport.ReplaceEnvVar(connectionURI)); Assert.IsNotNull(factory); using (IConnection connection = factory.CreateConnection("", "")) { Assert.IsNotNull(connection); using (ISession session = connection.CreateSession()) { Assert.IsNotNull(session as INetTxSession); IDestination destination = session.CreateTemporaryTopic(); using (IMessageProducer producer = session.CreateProducer(destination)) { producer.Close(); } using (IMessageConsumer consumer = session.CreateConsumer(destination)) { consumer.Close(); } session.Close(); } connection.Close(); } } }
public void DestroyMQConsumer(IMessageConsumer consumer) { if (consumer != null) { consumer.Close(); consumer.Dispose(); } }
public void TestFailoverToAnotherExclusiveConsumerCreatedFirst() { IConnection conn = createConnection(true); ISession exclusiveSession1 = null; ISession exclusiveSession2 = null; ISession fallbackSession = null; ISession senderSession = null; purgeQueue(conn, new ActiveMQQueue("TEST.QUEUE2")); try { exclusiveSession1 = conn.CreateSession(AcknowledgementMode.AutoAcknowledge); exclusiveSession2 = conn.CreateSession(AcknowledgementMode.AutoAcknowledge); fallbackSession = conn.CreateSession(AcknowledgementMode.AutoAcknowledge); senderSession = conn.CreateSession(AcknowledgementMode.AutoAcknowledge); // This creates the exclusive consumer first which avoids AMQ-1024 // bug. ActiveMQQueue exclusiveQueue = new ActiveMQQueue("TEST.QUEUE2?consumer.exclusive=true"); IMessageConsumer exclusiveConsumer1 = exclusiveSession1.CreateConsumer(exclusiveQueue); IMessageConsumer exclusiveConsumer2 = exclusiveSession2.CreateConsumer(exclusiveQueue); ActiveMQQueue fallbackQueue = new ActiveMQQueue("TEST.QUEUE2"); IMessageConsumer fallbackConsumer = fallbackSession.CreateConsumer(fallbackQueue); ActiveMQQueue senderQueue = new ActiveMQQueue("TEST.QUEUE2"); IMessageProducer producer = senderSession.CreateProducer(senderQueue); producer.DeliveryMode = MsgDeliveryMode.NonPersistent; IMessage msg = senderSession.CreateTextMessage("test"); producer.Send(msg); Thread.Sleep(500); // Verify exclusive consumer receives the message. Assert.IsNotNull(exclusiveConsumer1.Receive(TimeSpan.FromMilliseconds(1000))); Assert.IsNull(exclusiveConsumer2.Receive(TimeSpan.FromMilliseconds(1000))); Assert.IsNull(fallbackConsumer.Receive(TimeSpan.FromMilliseconds(1000))); // Close the exclusive consumer to verify the non-exclusive consumer // takes over exclusiveConsumer1.Close(); producer.Send(msg); producer.Send(msg); Assert.IsNotNull(exclusiveConsumer2.Receive(TimeSpan.FromMilliseconds(1000))); Assert.IsNull(fallbackConsumer.Receive(TimeSpan.FromMilliseconds(1000))); } finally { fallbackSession.Close(); senderSession.Close(); conn.Close(); } }
protected override void Receive(CancellationToken token, IConnection connection) { using (ISession session = connection.CreateSession(true, AcknowledgeMode.AutoAcknowledge)) { CurrentSessions.SetSession(session); token.Register(() => { if (consumer != null) { consumer.Close(); } }); using (consumer = createConsumer(session)) { while (!token.IsCancellationRequested) { IMessage message = consumer.Receive(); if (message != null) { Exception exception = null; TransportMessage transportMessage = null; try { transportMessage = ConvertMessage(message); if (ProcessMessage(transportMessage)) { session.Commit(); } else { session.Rollback(); } } catch (Exception ex) { Logger.Error("Error processing message.", ex); session.Rollback(); exception = ex; } finally { endProcessMessage(transportMessage, exception); } } } consumer.Close(); } session.Close(); } }
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); } }
public void TestIndividualAcknowledgeMultiMessages_AcknowledgeFirstTest() { ISession session = connection.CreateSession(AcknowledgementMode.IndividualAcknowledge); // Push 2 messages to queue ITemporaryQueue queue = session.CreateTemporaryQueue(); IMessageProducer producer = session.CreateProducer(queue); ITextMessage msg = session.CreateTextMessage("test 1"); producer.Send(msg, MsgDeliveryMode.Persistent, MsgPriority.Normal, TimeSpan.MinValue); msg = session.CreateTextMessage("test 2"); producer.Send(msg, MsgDeliveryMode.Persistent, MsgPriority.Normal, TimeSpan.MinValue); producer.Close(); IMessageConsumer consumer = session.CreateConsumer(queue); // Read the first message ITextMessage fetchedMessage1 = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(2000)); Assert.IsNotNull(fetchedMessage1); Assert.AreEqual("test 1", fetchedMessage1.Text); // Read the second message ITextMessage fetchedMessage2 = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(2000)); Assert.IsNotNull(fetchedMessage2); Assert.AreEqual("test 2", fetchedMessage2.Text); // Acknowledge first message fetchedMessage1.Acknowledge(); consumer.Close(); // Read first message a second time consumer = session.CreateConsumer(queue); fetchedMessage1 = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(2000)); Assert.IsNotNull(fetchedMessage1); Assert.AreEqual("test 2", fetchedMessage1.Text); // Try to read second message a second time fetchedMessage2 = (ITextMessage)consumer.Receive(TimeSpan.FromMilliseconds(2000)); Assert.IsNull(fetchedMessage2); consumer.Close(); }
public async Task TestMessageListenerClosesItsConsumer() { var latch = new ManualResetEvent(false); var exceptionListenerFired = new ManualResetEvent(false); using (TestAmqpPeer testPeer = new TestAmqpPeer()) { IConnection connection = await EstablishConnectionAsync(testPeer); await connection.StartAsync(); connection.ExceptionListener += _ => exceptionListenerFired.Set(); testPeer.ExpectBegin(); ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge); IQueue destination = await session.GetQueueAsync("myQueue"); await connection.StartAsync(); testPeer.ExpectReceiverAttach(); testPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithContent(), 1); IMessageConsumer consumer = await session.CreateConsumerAsync(destination); testPeer.ExpectLinkFlow(drain: true, sendDrainFlowResponse: true, creditMatcher: credit => Assert.AreEqual(99, credit)); // Not sure if expected credit is right testPeer.ExpectDispositionThatIsAcceptedAndSettled(); testPeer.ExpectDetach(expectClosed: true, sendResponse: true, replyClosed: true); Exception exception = null; consumer.Listener += message => { try { consumer.Close(); latch.Set(); } catch (Exception e) { exception = e; } }; Assert.True(latch.WaitOne(TimeSpan.FromMilliseconds(1000)), "Process not completed within given timeout"); Assert.IsNull(exception, "No error expected during close"); testPeer.WaitForAllMatchersToComplete(2000); testPeer.ExpectClose(); await connection.CloseAsync(); Assert.False(exceptionListenerFired.WaitOne(20), "Exception listener shouldn't have fired"); testPeer.WaitForAllMatchersToComplete(2000); } }
public void TestSendSessionClose() { IMessage[] outbound = new IMessage[] { session.CreateTextMessage("First IMessage"), session.CreateTextMessage("Second IMessage") }; // sends a message BeginTx(); producer.Send(outbound[0]); CommitTx(); // sends a message that gets rollbacked BeginTx(); producer.Send(session.CreateTextMessage("I'm going to get rolled back.")); consumer.Close(); ReconnectSession(); // sends a message producer.Send(outbound[1]); CommitTx(); // receives the first message LinkedList <IMessage> messages = new LinkedList <IMessage>(); BeginTx(); IMessage message = consumer.Receive(TimeSpan.FromMilliseconds(1000)); Assert.IsNotNull(message); messages.AddLast(message); // receives the second message message = consumer.Receive(TimeSpan.FromMilliseconds(5000)); Assert.IsNotNull(message); messages.AddLast(message); // validates that the rollbacked was not consumed CommitTx(); IMessage[] inbound = new IMessage[messages.Count]; messages.CopyTo(inbound, 0); AssertTextMessagesEqual(outbound, inbound, "Rollback did not work."); }
public void TestConsumeAfterPublishFailsForDestroyedTempDestination() { const string msgQueueName = "Test.RequestReply.MsgQueue"; Connection consumerConnection = GetNewConnection(); ISession consumerSession = consumerConnection.CreateSession(AcknowledgementMode.AutoAcknowledge); IDestination consumerDestination = consumerSession.GetQueue(msgQueueName); IMessageConsumer consumer = consumerSession.CreateConsumer(consumerDestination); consumerConnection.Start(); // Purge the destination before starting. while (consumer.Receive(TimeSpan.FromMilliseconds(3000)) != null) { } // The real test is whether sending a message to a deleted temp queue messes up // the consumers on the same connection. for (int index = 0; index < 25; index++) { Connection producerConnection = GetNewConnection(); ISession producerSession = producerConnection.CreateSession(AcknowledgementMode.AutoAcknowledge); IDestination producerDestination = producerSession.GetQueue(msgQueueName); IMessageProducer producer = producerSession.CreateProducer(producerDestination); IDestination replyDestination = producerSession.CreateTemporaryQueue(); IMessageConsumer replyConsumer = producerSession.CreateConsumer(replyDestination); producerConnection.Start(); IMessage sendMsg = producer.CreateTextMessage("Consumer check."); sendMsg.NMSReplyTo = replyDestination; producer.Send(sendMsg); // Will the following Receive() call fail on the second or subsequent calls? IMessage receiveMsg = consumer.Receive(); IMessageProducer replyProducer = consumerSession.CreateProducer(receiveMsg.NMSReplyTo); replyConsumer.Close(); connections.Remove(producerConnection); producerConnection.Close(); Thread.Sleep(2000); // Wait a little bit to let the delete take effect. // This message delivery NOT should work since the temp destination was removed by closing the connection. try { IMessage replyMsg = replyProducer.CreateTextMessage("Reply check."); replyProducer.Send(replyMsg); Assert.Fail("Send should fail since temp destination should not exist anymore."); } catch (NMSException e) { Tracer.Debug("Test threw expected exception: " + e.Message); } } }
//------------------------------------------------------------------------------ // // Method: Disconnect // //------------------------------------------------------------------------------ /// <summary> /// Disconnects from the message queue. /// </summary> public override void Disconnect() { CheckNotDisposed(); if (connected == true) { consumer.Close(); base.Disconnect(); loggingUtilities.Log(this, LogLevel.Information, "Disconnected."); } }
public void PurgeQueue(IConnection conn, IDestination queue) { ISession session = conn.CreateSession(); IMessageConsumer consumer = session.CreateConsumer(queue); while (consumer.Receive(TimeSpan.FromMilliseconds(500)) != null) { } consumer.Close(); session.Close(); }
/// <summary> /// </summary> /// <returns></returns> public override void Close() { if (_consumer != null) { _consumer.Close(); _consumer.Dispose(); _consumer = null; } base.Close(); }
public void ShouldCloseSessionWhenSubscriptionDisposed() { IDisposable subscription = _source.Messages.Subscribe(_observer); subscription.Dispose(); A.CallTo(() => _consumer.Close()).MustHaveHappened(Repeated.Exactly.Once); A.CallTo(() => _consumer.Dispose()).MustHaveHappened(Repeated.Exactly.Once); A.CallTo(() => _session.Close()).MustHaveHappened(Repeated.Exactly.Once); A.CallTo(() => _session.Dispose()).MustHaveHappened(Repeated.Exactly.Once); }
public void TestOptimizedAckWithExpiredMsgs() { ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge); IDestination destination = session.GetQueue("TestOptimizedAckWithExpiredMsgs"); IMessageConsumer consumer = session.CreateConsumer(destination); IMessageProducer producer = session.CreateProducer(destination); producer.DeliveryMode = MsgDeliveryMode.NonPersistent; ITextMessage message; // Produce msgs that will expire quickly for (int i = 0; i < 45; i++) { message = session.CreateTextMessage(); producer.Send(message, MsgDeliveryMode.NonPersistent, MsgPriority.Normal, TimeSpan.FromMilliseconds(200)); } // Produce msgs that don't expire for (int i = 0; i < 60; i++) { message = session.CreateTextMessage(); producer.Send(message, MsgDeliveryMode.NonPersistent, MsgPriority.Normal, TimeSpan.FromMilliseconds(60000)); } Thread.Sleep(1000); // let the batch of 45 expire. consumer.Listener += OnMessage; connection.Start(); for (int i = 0; i < 60; ++i) { if (counter == 60) { break; } Thread.Sleep(1000); } Assert.AreEqual(60, counter, "Failed to receive all expected messages"); // Cleanup producer.Close(); consumer.Close(); session.Close(); connection.Close(); }
void tm_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { try { if (GetActiveMQConnection(SingletonInfo.GetInstance().CheckMQURL)) { //连接正常 if (!isConn) { DealMqConnection(); } } else { LogMessage("MQ服务器未连接!"); LogHelper.WriteLog(typeof(MainForm), "打开MQ网站出错", "2");//日志测试 20180319 isConn = false; //连接异常 m_consumer.Close(); if (SingletonInfo.GetInstance().m_mq != null) { SingletonInfo.GetInstance().m_mq.Close(); } SingletonInfo.GetInstance().m_mq = null; GC.Collect(); } } catch (Exception ex) { isConn = false; //连接异常 m_consumer.Close(); if (SingletonInfo.GetInstance().m_mq != null) { SingletonInfo.GetInstance().m_mq.Close(); } SingletonInfo.GetInstance().m_mq = null; GC.Collect(); } }
private void DoRemotelyCloseConsumerWithMessageListenerFiresNMSExceptionListenerTestImpl(bool closeWithError) { using (TestAmqpPeer testPeer = new TestAmqpPeer(Address1, User, Password)) { ManualResetEvent consumerClosed = new ManualResetEvent(false); ManualResetEvent exceptionListenerFired = new ManualResetEvent(false); TestLinkProcessor linkProcessor = new TestLinkProcessor(); testPeer.RegisterLinkProcessor(linkProcessor); testPeer.Open(); NmsConnection connection = EstablishConnection("failover.maxReconnectAttempts=1", testPeer); connection.ExceptionListener += exception => { exceptionListenerFired.Set(); }; Mock <INmsConnectionListener> connectionListener = new Mock <INmsConnectionListener>(); connectionListener .Setup(listener => listener.OnConsumerClosed(It.IsAny <IMessageConsumer>(), It.IsAny <Exception>())) .Callback(() => { consumerClosed.Set(); }); connection.AddConnectionListener(connectionListener.Object); connection.Start(); ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge); IQueue queue = session.GetQueue("myQueue"); // Create a consumer, then remotely end it afterwards. IMessageConsumer consumer = session.CreateConsumer(queue); consumer.Listener += message => { }; if (closeWithError) { linkProcessor.CloseConsumerWithError(); } else { linkProcessor.CloseConsumer(); } Assert.True(consumerClosed.WaitOne(TimeSpan.FromMilliseconds(2000)), "Consumer closed callback didn't trigger"); Assert.True(exceptionListenerFired.WaitOne(TimeSpan.FromMilliseconds(2000)), "JMS Exception listener should have fired with a MessageListener"); // Try closing it explicitly, should effectively no-op in client. // The test peer will throw during close if it sends anything. consumer.Close(); connection.Close(); } }
public void TestMessageListenerCallsSessionCloseThrowsIllegalStateException() { using (TestAmqpPeer testPeer = new TestAmqpPeer()) { IConnection connection = EstablishConnection(testPeer); connection.Start(); testPeer.ExpectBegin(); ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge); IQueue destination = session.GetQueue("myQueue"); connection.Start(); testPeer.ExpectReceiverAttach(); testPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithContent(), 1); IMessageConsumer consumer = session.CreateConsumer(destination); testPeer.ExpectDispositionThatIsAcceptedAndSettled(); ManualResetEvent latch = new ManualResetEvent(false); Exception exception = null; consumer.Listener += message => { try { session.Close(); } catch (Exception e) { exception = e; } latch.Set(); }; Assert.True(latch.WaitOne(3000), "Messages not received within given timeout."); Assert.IsNotNull(exception); Assert.IsInstanceOf <IllegalStateException>(exception); testPeer.WaitForAllMatchersToComplete(2000); testPeer.ExpectDetach(expectClosed: true, sendResponse: true, replyClosed: true); consumer.Close(); testPeer.ExpectClose(); connection.Close(); testPeer.WaitForAllMatchersToComplete(2000); } }
private void Disconnect() { try { if (moConnection != null) { try { if (moConnection != null) { moConnection.Stop(); } } catch { } try { if (moConsumer1 != null) { moConsumer1.Close(); } } catch { } try { if (moConsumer2 != null) { moConsumer2.Close(); } } catch { } try { if (moSession != null) { moSession.Close(); } } catch { } try { if (moConnection != null) { moConnection.Close(); } } catch { } } } finally { moConnection = null; moConnectionFactory = null; moSession = null; moTopic1 = null; moTopic2 = null; moConsumer1 = null; moConsumer2 = null; Interlocked.Exchange(ref miIsConnected, 0); } }
public void TestMessageListenerClosesItsConsumer() { using (TestAmqpPeer testAmqpPeer = new TestAmqpPeer(Address, User, Password)) { testAmqpPeer.Open(); TestLinkProcessor testLinkProcessor = new TestLinkProcessor(); testAmqpPeer.RegisterLinkProcessor(testLinkProcessor); testAmqpPeer.SendMessage("myQueue", "test"); NmsConnection connection = (NmsConnection)EstablishConnection(); connection.Start(); ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge); IQueue destination = session.GetQueue("myQueue"); IMessageConsumer consumer = session.CreateConsumer(destination); ManualResetEvent latch = new ManualResetEvent(false); Exception exception = null; consumer.Listener += message => { try { consumer.Close(); latch.Set(); } catch (Exception e) { exception = e; } }; Assert.True(latch.WaitOne(TimeSpan.FromMilliseconds(1000))); Assert.That(() => testLinkProcessor.Consumer, Is.Null.After(1000, 50)); consumer.Close(); session.Close(); connection.Close(); } }
/// <summary> Close the given NMS MessageConsumer and ignore any thrown exception. /// This is useful for typical <code>finally</code> blocks in manual NMS code. /// </summary> /// <param name="consumer">the NMS MessageConsumer to close (may be <code>null</code>) /// </param> public static void CloseMessageConsumer(IMessageConsumer consumer) { if (consumer != null) { try { consumer.Close(); } catch (NMSException ex) { logger.Debug("Could not close NMS MessageConsumer", ex); } catch (Exception ex) { // We don't trust the NMS provider: It might throw RuntimeException or Error. logger.Debug("Unexpected exception on closing NMS MessageConsumer", ex); } } }