Search in sources :

Example 71 with MessageListener

use of javax.jms.MessageListener in project activemq-artemis by apache.

the class MiscellaneousTest method testClosingConsumerFromMessageListenerTransacted.

/**
 * Test case for http://jira.jboss.org/jira/browse/JBMESSAGING-542
 */
@Test
public void testClosingConsumerFromMessageListenerTransacted() throws Exception {
    Connection c = null;
    try {
        c = createConnection();
        Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer prod = s.createProducer(queue1);
        Message m = s.createMessage();
        prod.send(m);
    } finally {
        if (c != null) {
            c.close();
        }
    }
    final Result result = new Result();
    Connection conn = createConnection();
    Session s = conn.createSession(true, Session.SESSION_TRANSACTED);
    final MessageConsumer cons = s.createConsumer(queue1);
    cons.setMessageListener(new MessageListener() {

        @Override
        public void onMessage(final Message m) {
            // close the connection on the same thread that processed the message
            try {
                cons.close();
                result.setSuccess();
            } catch (Exception e) {
                result.setFailure(e);
            }
        }
    });
    conn.start();
    result.waitForResult();
    ProxyAssertSupport.assertTrue(result.isSuccess());
    ProxyAssertSupport.assertNull(result.getFailure());
    Thread.sleep(1000);
    assertRemainingMessages(1);
    conn.close();
}
Also used : MessageConsumer(javax.jms.MessageConsumer) TextMessage(javax.jms.TextMessage) Message(javax.jms.Message) Connection(javax.jms.Connection) MessageListener(javax.jms.MessageListener) MessageProducer(javax.jms.MessageProducer) Session(javax.jms.Session) Test(org.junit.Test)

Example 72 with MessageListener

use of javax.jms.MessageListener in project activemq-artemis by apache.

the class DurableSubscriptionSelectorTest method openConsumer.

private void openConsumer() throws Exception {
    consumerConnection = (ActiveMQConnection) createConnection();
    consumerConnection.setClientID("cliID");
    consumerConnection.start();
    Session session = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    TopicSubscriber subscriber = session.createDurableSubscriber(topic, "subName", "filter=true", false);
    subscriber.setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message message) {
            received++;
        }
    });
}
Also used : TopicSubscriber(javax.jms.TopicSubscriber) Message(javax.jms.Message) MessageListener(javax.jms.MessageListener) Session(javax.jms.Session)

Example 73 with MessageListener

use of javax.jms.MessageListener in project activemq-artemis by apache.

the class ExpiredMessagesWithNoConsumerTest method testExpiredMessagesWithVerySlowConsumerCanContinue.

public void testExpiredMessagesWithVerySlowConsumerCanContinue() throws Exception {
    createBroker();
    final long queuePrefetch = 600;
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionUri + "?jms.prefetchPolicy.queuePrefetch=" + queuePrefetch);
    connection = factory.createConnection();
    session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    producer = session.createProducer(destination);
    final int ttl = 4000;
    producer.setTimeToLive(ttl);
    final long sendCount = 1500;
    final CountDownLatch receivedOneCondition = new CountDownLatch(1);
    final CountDownLatch waitCondition = new CountDownLatch(1);
    final AtomicLong received = new AtomicLong();
    MessageConsumer consumer = session.createConsumer(destination);
    consumer.setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message message) {
            try {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Got my message: " + message);
                }
                receivedOneCondition.countDown();
                received.incrementAndGet();
                waitCondition.await(5, TimeUnit.MINUTES);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("acking message: " + message);
                }
                message.acknowledge();
            } catch (Exception e) {
                e.printStackTrace();
                fail(e.toString());
            }
        }
    });
    connection.start();
    final Thread producingThread = new Thread("Producing Thread") {

        @Override
        public void run() {
            try {
                int i = 0;
                long tStamp = System.currentTimeMillis();
                while (i++ < sendCount) {
                    producer.send(session.createTextMessage("test"));
                    if (i % 100 == 0) {
                        LOG.info("sent: " + i + " @ " + ((System.currentTimeMillis() - tStamp) / 100) + "m/ms");
                        tStamp = System.currentTimeMillis();
                    }
                }
            } catch (Throwable ex) {
                ex.printStackTrace();
            }
        }
    };
    producingThread.start();
    assertTrue("got one message", receivedOneCondition.await(20, TimeUnit.SECONDS));
    assertTrue("producer failed to complete within allocated time", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            producingThread.join(1000);
            return !producingThread.isAlive();
        }
    }, Wait.MAX_WAIT_MILLIS * 10));
    final DestinationViewMBean view = createView(destination);
    assertTrue("Not all dispatched up to default prefetch ", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            return queuePrefetch == view.getDispatchCount();
        }
    }));
    assertTrue("all non inflight have expired ", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() + ", size= " + view.getQueueSize());
            return view.getExpiredCount() > 0 && (view.getEnqueueCount() - view.getInFlightCount()) == view.getExpiredCount();
        }
    }));
    LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() + ", size= " + view.getQueueSize());
    // let the ack happen
    waitCondition.countDown();
    Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            return 0 == view.getInFlightCount();
        }
    });
    LOG.info("enqueue=" + view.getEnqueueCount() + ", dequeue=" + view.getDequeueCount() + ", inflight=" + view.getInFlightCount() + ", expired= " + view.getExpiredCount() + ", size= " + view.getQueueSize());
    assertEquals("inflight didn't reduce to duck", 0, view.getInFlightCount());
    assertEquals("size doesn't get back to 0 ", 0, view.getQueueSize());
    assertEquals("dequeues don't match sent/expired ", sendCount, view.getDequeueCount());
    // produce some more
    producer.setTimeToLive(0);
    long tStamp = System.currentTimeMillis();
    for (int i = 0; i < sendCount; i++) {
        producer.send(session.createTextMessage("test-" + i));
        if (i % 100 == 0) {
            LOG.info("sent: " + i + " @ " + ((System.currentTimeMillis() - tStamp) / 100) + "m/ms");
            tStamp = System.currentTimeMillis();
        }
    }
    Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            return received.get() >= sendCount;
        }
    });
    consumer.close();
    Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            return 0 == view.getInFlightCount();
        }
    });
    assertEquals("inflight did not go to zero on close", 0, view.getInFlightCount());
    LOG.info("done: " + getName());
}
Also used : DestinationViewMBean(org.apache.activemq.broker.jmx.DestinationViewMBean) MessageConsumer(javax.jms.MessageConsumer) Message(javax.jms.Message) MessageListener(javax.jms.MessageListener) CountDownLatch(java.util.concurrent.CountDownLatch) ActiveMQConnectionFactory(org.apache.activemq.ActiveMQConnectionFactory) AtomicLong(java.util.concurrent.atomic.AtomicLong) Wait(org.apache.activemq.util.Wait)

Example 74 with MessageListener

use of javax.jms.MessageListener in project e3mall by colg-cloud.

the class ActiveMqTest method testQueueConsumer.

/**
 * 点对点模式,接收消息
 */
@Test
public void testQueueConsumer() throws JMSException, IOException {
    // 第一步:创建一个ConnectionFactory对象。
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROCKER_URL);
    // 第二步:从ConnectionFactory对象中获得一个Connection对象。
    Connection connection = connectionFactory.createConnection();
    // 第三步:开启连接。调用Connection对象的start方法。
    connection.start();
    // 第四步:使用Connection对象创建一个Session对象。
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    // 第五步:使用Session对象创建一个Destination对象。和发送端保持一致queue,并且队列的名称一致。
    Queue queue = session.createQueue("test-queue");
    // 第六步:使用Session对象创建一个Consumer对象。
    MessageConsumer consumer = session.createConsumer(queue);
    // 第七步:接收消息。
    consumer.setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message message) {
            try {
                TextMessage textMessage = (TextMessage) message;
                // 取消息的内容
                String text = textMessage.getText();
                // 第八步:打印消息。
                LOGGER.info("队列模式接收到的消息: {}", text);
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    });
    // 等待键盘输入
    System.in.read();
    // 第九步:关闭资源
    consumer.close();
    session.close();
    connection.close();
}
Also used : ActiveMQConnectionFactory(org.apache.activemq.ActiveMQConnectionFactory) ActiveMQConnectionFactory(org.apache.activemq.ActiveMQConnectionFactory) ConnectionFactory(javax.jms.ConnectionFactory) MessageConsumer(javax.jms.MessageConsumer) TextMessage(javax.jms.TextMessage) Message(javax.jms.Message) Connection(javax.jms.Connection) MessageListener(javax.jms.MessageListener) JMSException(javax.jms.JMSException) Queue(javax.jms.Queue) TextMessage(javax.jms.TextMessage) Session(javax.jms.Session) Test(org.junit.Test)

Example 75 with MessageListener

use of javax.jms.MessageListener in project wildfly by wildfly.

the class JmsClientTestCase method doSendAndReceive.

private void doSendAndReceive(String connectionFactoryLookup) throws Exception {
    Connection conn = null;
    try {
        ConnectionFactory cf = (ConnectionFactory) remoteContext.lookup(connectionFactoryLookup);
        assertNotNull(cf);
        Destination destination = (Destination) remoteContext.lookup(QUEUE_NAME);
        assertNotNull(destination);
        conn = cf.createConnection("guest", "guest");
        conn.start();
        Session consumerSession = conn.createSession(false, AUTO_ACKNOWLEDGE);
        final CountDownLatch latch = new CountDownLatch(10);
        final List<String> result = new ArrayList<String>();
        // Set the async listener
        MessageConsumer consumer = consumerSession.createConsumer(destination);
        consumer.setMessageListener(new MessageListener() {

            @Override
            public void onMessage(Message message) {
                TextMessage msg = (TextMessage) message;
                try {
                    result.add(msg.getText());
                    latch.countDown();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });
        final Session producerSession = conn.createSession(false, AUTO_ACKNOWLEDGE);
        MessageProducer producer = producerSession.createProducer(destination);
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        for (int i = 0; i < 10; i++) {
            String s = "Test" + i;
            TextMessage msg = producerSession.createTextMessage(s);
            // System.out.println("sending " + s);
            producer.send(msg);
        }
        producerSession.close();
        assertTrue(latch.await(3, SECONDS));
        assertEquals(10, result.size());
        for (int i = 0; i < result.size(); i++) {
            assertEquals("Test" + i, result.get(i));
        }
    } finally {
        try {
            conn.close();
        } catch (Exception ignore) {
        }
    }
}
Also used : Destination(javax.jms.Destination) MessageConsumer(javax.jms.MessageConsumer) Message(javax.jms.Message) TextMessage(javax.jms.TextMessage) Connection(javax.jms.Connection) ArrayList(java.util.ArrayList) MessageListener(javax.jms.MessageListener) JMSException(javax.jms.JMSException) CountDownLatch(java.util.concurrent.CountDownLatch) IOException(java.io.IOException) JMSException(javax.jms.JMSException) ConnectionFactory(javax.jms.ConnectionFactory) MessageProducer(javax.jms.MessageProducer) TextMessage(javax.jms.TextMessage) Session(javax.jms.Session)

Aggregations

MessageListener (javax.jms.MessageListener)146 Message (javax.jms.Message)128 MessageConsumer (javax.jms.MessageConsumer)103 Session (javax.jms.Session)97 TextMessage (javax.jms.TextMessage)95 CountDownLatch (java.util.concurrent.CountDownLatch)72 Test (org.junit.Test)71 Connection (javax.jms.Connection)60 MessageProducer (javax.jms.MessageProducer)58 JMSException (javax.jms.JMSException)57 Destination (javax.jms.Destination)32 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)31 ActiveMQConnectionFactory (org.apache.activemq.ActiveMQConnectionFactory)26 BytesMessage (javax.jms.BytesMessage)22 Queue (javax.jms.Queue)21 ConnectionFactory (javax.jms.ConnectionFactory)16 ScheduledMessage (org.apache.activemq.ScheduledMessage)15 ArrayList (java.util.ArrayList)14 Topic (javax.jms.Topic)13 ActiveMQQueue (org.apache.activemq.command.ActiveMQQueue)13