當前位置: 首頁>>代碼示例>>Java>>正文


Java MessageConsumer.receive方法代碼示例

本文整理匯總了Java中javax.jms.MessageConsumer.receive方法的典型用法代碼示例。如果您正苦於以下問題:Java MessageConsumer.receive方法的具體用法?Java MessageConsumer.receive怎麽用?Java MessageConsumer.receive使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在javax.jms.MessageConsumer的用法示例。


在下文中一共展示了MessageConsumer.receive方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: receiveAndRespondWithMessageIdAsCorrelationId

import javax.jms.MessageConsumer; //導入方法依賴的package包/類
public void receiveAndRespondWithMessageIdAsCorrelationId(ConnectionFactory connectionFactory, String queueName) throws JMSException {
    Connection connection = connectionFactory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(session.createQueue(queueName));
    final javax.jms.Message inMessage = consumer.receive();

    String requestMessageId = inMessage.getJMSMessageID();
    LOG.debug("Received message " + requestMessageId);
    final TextMessage replyMessage = session.createTextMessage("Result");
    replyMessage.setJMSCorrelationID(inMessage.getJMSMessageID());
    final MessageProducer producer = session.createProducer(inMessage.getJMSReplyTo());
    LOG.debug("Sending reply to " + inMessage.getJMSReplyTo());
    producer.send(replyMessage);

    producer.close();
    consumer.close();
    session.close();
    connection.close();
}
 
開發者ID:messaginghub,項目名稱:pooled-jms,代碼行數:20,代碼來源:PooledConnectionTempQueueTest.java

示例2: testReceive

import javax.jms.MessageConsumer; //導入方法依賴的package包/類
@Test
public void testReceive() throws JMSException {
    JmsPoolConnection connection = (JmsPoolConnection) cf.createQueueConnection();
    Session session = connection.createSession();
    Queue queue = session.createTemporaryQueue();
    MessageConsumer consumer = session.createConsumer(queue, "Color = Red");

    assertNull(consumer.receive());

    consumer.close();

    try {
        consumer.receive();
        fail("Should not be able to interact with closed consumer");
    } catch (IllegalStateException ise) {}
}
 
開發者ID:messaginghub,項目名稱:pooled-jms,代碼行數:17,代碼來源:JmsPoolMessageConusmerTest.java

示例3: testReceiveTimed

import javax.jms.MessageConsumer; //導入方法依賴的package包/類
@Test
public void testReceiveTimed() throws JMSException {
    JmsPoolConnection connection = (JmsPoolConnection) cf.createQueueConnection();
    Session session = connection.createSession();
    Queue queue = session.createTemporaryQueue();
    MessageConsumer consumer = session.createConsumer(queue, "Color = Red");

    assertNull(consumer.receive(1));

    consumer.close();

    try {
        consumer.receive(1);
        fail("Should not be able to interact with closed consumer");
    } catch (IllegalStateException ise) {}
}
 
開發者ID:messaginghub,項目名稱:pooled-jms,代碼行數:17,代碼來源:JmsPoolMessageConusmerTest.java

示例4: sendWithReplyToTemp

import javax.jms.MessageConsumer; //導入方法依賴的package包/類
private void sendWithReplyToTemp(ConnectionFactory cf, String serviceQueue) throws JMSException, InterruptedException {
    Connection connection = cf.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    TemporaryQueue tempQueue = session.createTemporaryQueue();
    TextMessage msg = session.createTextMessage("Request");
    msg.setJMSReplyTo(tempQueue);
    MessageProducer producer = session.createProducer(session.createQueue(serviceQueue));
    producer.send(msg);

    MessageConsumer consumer = session.createConsumer(tempQueue);
    Message replyMsg = consumer.receive();
    assertNotNull(replyMsg);

    LOG.debug("Reply message: {}", replyMsg);

    consumer.close();

    producer.close();
    session.close();
    connection.close();
}
 
開發者ID:messaginghub,項目名稱:pooled-jms,代碼行數:23,代碼來源:PooledConnectionTempQueueTest.java

示例5: consumeMessage

import javax.jms.MessageConsumer; //導入方法依賴的package包/類
/** Deletes the input Message from the given Queue, by creating a temporary consumer for that Message
 * @param session the JMS Session.
 * @param message the JMS Message.
 * @param queueName the Queue to consume from.
 * @throws FrameworkException in case any internal error occurs.
 * @throws ApplicationExceptions Indicates application error(s).
 */
static void consumeMessage(Session session, Message message, String queueName) throws FrameworkException, ApplicationExceptions {
    try {
        // Creates a consumer on the session for the given queueName, and specifying a selector having HEADER_JMS_MESSAGE_ID as the given messageId
        String selector = new StringBuilder(HEADER_JMS_MESSAGE_ID)
        .append("='")
        .append(message.getJMSMessageID())
        .append('\'')
        .toString();
        MessageConsumer consumer = session.createConsumer(JmsClientHelper.obtainQueue(queueName), selector);
        
        // Consume the message. Wait for 10 seconds at most
        Message m = consumer.receive(10000);
        if (m == null)
            throw new ApplicationExceptions(new JaffaMessagingApplicationException(JaffaMessagingApplicationException.MESSAGE_NOT_FOUND));
        consumer.close();
    } catch (JMSException e) {
        log.error("Error in consuming a JMS Message", e);
        throw new JaffaMessagingFrameworkException(JaffaMessagingFrameworkException.DELETE_ERROR, null, e);
    }
}
 
開發者ID:jaffa-projects,項目名稱:jaffa-framework,代碼行數:28,代碼來源:JmsBrowser.java

示例6: startSyncReceiveThread

import javax.jms.MessageConsumer; //導入方法依賴的package包/類
private void startSyncReceiveThread(final MessageConsumer messageConsumer, final long receiveTimeout) {
    syncReceiveThread = new SyncReceiveThread() {
        @Override
        public void run() {
            log.info("start listen to the " + typeStr + "[" + queue.getName() + "].");
            while (running) {
                try {
                    Message message = messageConsumer.receive(receiveTimeout);
                    processMessage(message);
                } catch (Throwable e) {
                    // 如果是關閉的時候,可能會報InterruptedException
                    log.error("listen to the [" + queue.getName() + "] error.", e);
                }
            }
            closed = true;
        }
    };
    syncReceiveThread.start();
}
 
開發者ID:xsonorg,項目名稱:tangyuan2,代碼行數:20,代碼來源:ActiveMqReceiver.java

示例7: main

import javax.jms.MessageConsumer; //導入方法依賴的package包/類
public static void main(String[] args) {

        try {

            // Create a ConnectionFactory
            ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://Toshiba:61616");

            // Create a Connection
            Connection connection = connectionFactory.createConnection();
            connection.start();


            // Create a Session
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            // Create the destination (Topic or Queue)
            Destination destination = session.createQueue("HELLOWORLD.TESTQ");

            // Create a MessageConsumer from the Session to the Topic or Queue
            MessageConsumer consumer = session.createConsumer(destination);

            // Wait for a message
            Message message = consumer.receive(1000);

            if (message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;
                String text = textMessage.getText();
                System.out.println("Received: " + text);
            } else {
                System.out.println("Received: " + message);
            }

            consumer.close();
            session.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    
    }
 
開發者ID:Illusionist80,項目名稱:SpringTutorial,代碼行數:41,代碼來源:HelloWorldConsumer.java

示例8: run

import javax.jms.MessageConsumer; //導入方法依賴的package包/類
public void run() {
    try {

        // Create a ConnectionFactory
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://Toshiba:61616");

        // Create a Connection
        Connection connection = connectionFactory.createConnection();
        connection.start();

        connection.setExceptionListener(this);

        // Create a Session
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        // Create the destination (Topic or Queue)
        Destination destination = session.createQueue("HELLOWORLD.TESTQ");

        // Create a MessageConsumer from the Session to the Topic or Queue
        MessageConsumer consumer = session.createConsumer(destination);

        // Wait for a message
        Message message = consumer.receive(1000);

        if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            String text = textMessage.getText();
            System.out.println("Received: " + text);
        } else {
            System.out.println("Received: " + message);
        }

        consumer.close();
        session.close();
        connection.close();
    } catch (Exception e) {
        System.out.println("Caught: " + e);
        e.printStackTrace();
    }
}
 
開發者ID:Illusionist80,項目名稱:SpringTutorial,代碼行數:41,代碼來源:HelloWorldConsumerThread.java

示例9: testConsumerProducerWithSsl

import javax.jms.MessageConsumer; //導入方法依賴的package包/類
@Parameters({ "broker-ssl-port"})
@Test
public void testConsumerProducerWithSsl(String port) throws Exception {
    String queueName = "testConsumerProducerWithAutoAck";
    InitialContext initialContextForQueue = ClientHelper
            .getInitialContextBuilder("admin", "admin", "localhost", port)
            .enableSsl()
            .withQueue(queueName)
            .build();

    ConnectionFactory connectionFactory
            = (ConnectionFactory) initialContextForQueue.lookup(ClientHelper.CONNECTION_FACTORY);
    Connection connection = connectionFactory.createConnection();
    connection.start();

    // publish 100 messages
    Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = producerSession.createQueue(queueName);
    MessageProducer producer = producerSession.createProducer(queue);

    int numberOfMessages = 100;
    for (int i = 0; i < numberOfMessages; i++) {
        producer.send(producerSession.createTextMessage("Test message " + i));
    }
    producerSession.close();

    // Consume published messages
    Session subscriberSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination subscriberDestination = (Destination) initialContextForQueue.lookup(queueName);
    MessageConsumer consumer = subscriberSession.createConsumer(subscriberDestination);

    for (int i = 0; i < numberOfMessages; i++) {
        Message message = consumer.receive(1000);
        Assert.assertNotNull(message, "Message #" + i + " was not received");
    }

    connection.close();
}
 
開發者ID:wso2,項目名稱:message-broker,代碼行數:39,代碼來源:SslTransportTest.java

示例10: testConsumerProducerWithAutoAck

import javax.jms.MessageConsumer; //導入方法依賴的package包/類
@Parameters({ "broker-port"})
@Test
public void testConsumerProducerWithAutoAck(String port) throws Exception {
    String queueName = "testConsumerProducerWithAutoAck";
    InitialContext initialContextForQueue = ClientHelper
            .getInitialContextBuilder("admin", "admin", "localhost", port)
            .withQueue(queueName)
            .build();

    ConnectionFactory connectionFactory
            = (ConnectionFactory) initialContextForQueue.lookup(ClientHelper.CONNECTION_FACTORY);
    Connection connection = connectionFactory.createConnection();
    connection.start();

    // publish 100 messages
    Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = producerSession.createQueue(queueName);
    MessageProducer producer = producerSession.createProducer(queue);

    int numberOfMessages = 100;
    for (int i = 0; i < numberOfMessages; i++) {
        producer.send(producerSession.createTextMessage("Test message " + i));
    }
    producerSession.close();

    // Consume published messages
    Session subscriberSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination subscriberDestination = (Destination) initialContextForQueue.lookup(queueName);
    MessageConsumer consumer = subscriberSession.createConsumer(subscriberDestination);

    for (int i = 0; i < numberOfMessages; i++) {
        Message message = consumer.receive(5000);
        Assert.assertNotNull(message, "Message #" + i + " was not received");
    }

    connection.close();
}
 
開發者ID:wso2,項目名稱:message-broker,代碼行數:38,代碼來源:QueueConsumerTest.java

示例11: sendReceiveForNode

import javax.jms.MessageConsumer; //導入方法依賴的package包/類
private void sendReceiveForNode(String queueName, String hostname, String port) throws Exception {
    InitialContext initialContextForQueue = ClientHelper
            .getInitialContextBuilder("admin", "admin", hostname, port)
            .withQueue(queueName)
            .build();

    ConnectionFactory connectionFactory
            = (ConnectionFactory) initialContextForQueue.lookup(ClientHelper.CONNECTION_FACTORY);
    Connection connection = connectionFactory.createConnection();
    connection.start();

    Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = producerSession.createQueue(queueName);
    MessageProducer producer = producerSession.createProducer(queue);

    int numberOfMessages = 10;
    for (int i = 0; i < numberOfMessages; i++) {
        producer.send(producerSession.createTextMessage("Test message " + i));
    }
    producerSession.close();

    // Consume published messages
    Session subscriberSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination subscriberDestination = (Destination) initialContextForQueue.lookup(queueName);
    MessageConsumer consumer = subscriberSession.createConsumer(subscriberDestination);

    for (int i = 0; i < numberOfMessages; i++) {
        Message message = consumer.receive(5000);
        Assert.assertNotNull(message, "Message #" + i + " was not received");
    }

    connection.close();
}
 
開發者ID:wso2,項目名稱:message-broker,代碼行數:34,代碼來源:RdbmsHaStrategyTest.java

示例12: testSimpleSubmission

import javax.jms.MessageConsumer; //導入方法依賴的package包/類
@Test
public void testSimpleSubmission() throws Exception {

    StatusBean bean = doSubmit();

    // Manually take the submission from the list not using event service for isolated test
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(submitter.getUri());
    Connection connection = connectionFactory.createConnection();

    try {
        Session   session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(IEventService.SUBMISSION_QUEUE);

        final MessageConsumer consumer = session.createConsumer(queue);
        connection.start();

        TextMessage msg = (TextMessage)consumer.receive(1000);

        IMarshallerService marshaller = new MarshallerService(new PointsModelMarshaller());
        StatusBean fromQ = marshaller.unmarshal(msg.getText(), StatusBean.class);

    if (!fromQ.equals(bean)) throw new Exception("The bean from the queue was not the same as that submitted! q="+fromQ+" submit="+bean);

    } finally {
        consumer.disconnect();
        connection.close();
    }
}
 
開發者ID:eclipse,項目名稱:scanning,代碼行數:29,代碼來源:AbstractConsumerTest.java

示例13: requeueFailedMessages

import javax.jms.MessageConsumer; //導入方法依賴的package包/類
@Override
public void requeueFailedMessages() {
    try {
        ActiveMQConnection connection = ActiveMqUtils.openConnection(user, password, url);
        Session session = ActiveMqUtils.startSession(connection);

        int count = getQueueSize(session, queueError);

        if (count < 1) {
            return;
        }

        log.info("Requeuing {} failed messages...", count);

        Queue queueErr = session.createQueue(queueError);
        MessageConsumer consumer = session.createConsumer(queueErr);

        Queue queueRetry = session.createQueue(queueInput);
        MessageProducer producer = session.createProducer(queueRetry);

        for (int consumed = 0; consumed < count; consumed++) {
            TextMessage message = (TextMessage) consumer.receive(REQUEUE_TIMEOUT);

            if (message == null) {
                continue;
            }

            String text = message.getText();
            String requestId = message.getJMSCorrelationID();

            log.info("Requeuing message '{}'", text);

            try {
                TextMessage newMessage = session.createTextMessage(text);
                newMessage.setJMSCorrelationID(requestId);

                producer.send(newMessage);
            } catch (Exception e) {
                log.error("Failed to requeue message", e);
            }

            message.acknowledge();
            session.commit();
        }

        producer.close();
        consumer.close();
    } catch (JMSException ex) {
        throw new MessageQueueException("Failed to requeue failed messages", ex);
    }
}
 
開發者ID:code-obos,項目名稱:servicebuilder,代碼行數:52,代碼來源:ActiveMqListener.java

示例14: testCanExhaustSessions

import javax.jms.MessageConsumer; //導入方法依賴的package包/類
@Test(timeout = 60000)
public void testCanExhaustSessions() throws Exception {
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionUri);
                Connection connection = connectionFactory.createConnection();
                connection.start();

                Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                Destination destination = session.createQueue(QUEUE);
                MessageConsumer consumer = session.createConsumer(destination);
                for (int i = 0; i < NUM_MESSAGES; ++i) {
                    Message msg = consumer.receive(5000);
                    if (msg == null) {
                        return;
                    }
                    numReceived++;
                    if (numReceived % 20 == 0) {
                        LOG.debug("received " + numReceived + " messages ");
                        System.runFinalization();
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    });
    thread.start();

    ExecutorService threads = Executors.newFixedThreadPool(2);
    final CyclicBarrier barrier = new CyclicBarrier(2, new Runnable() {

        @Override
        public void run() {
            LOG.trace("Starting threads to send messages!");
        }
    });

    threads.execute(new TestRunner(barrier));
    threads.execute(new TestRunner(barrier));

    thread.join();

    // we should expect that one of the threads will die because it cannot acquire a session,
    // will throw an exception
    assertEquals(NUM_MESSAGES, numReceived);
    assertEquals(exceptionList.size(), 1);
}
 
開發者ID:messaginghub,項目名稱:pooled-jms,代碼行數:51,代碼來源:PooledSessionExhaustionTest.java

示例15: testCanExhaustSessions

import javax.jms.MessageConsumer; //導入方法依賴的package包/類
@Test(timeout = 60000)
public void testCanExhaustSessions() throws Exception {
    final int totalMessagesExpected =  NUM_MESSAGES * 2;
    final CountDownLatch latch = new CountDownLatch(2);
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionUri);
                Connection connection = connectionFactory.createConnection();
                connection.start();

                Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                Destination destination = session.createQueue(QUEUE);
                MessageConsumer consumer = session.createConsumer(destination);
                for (int i = 0; i < totalMessagesExpected; ++i) {
                    Message msg = consumer.receive(5000);
                    if (msg == null) {
                        return;
                    }
                    numReceived++;
                    if (numReceived % 20 == 0) {
                        LOG.debug("received " + numReceived + " messages ");
                        System.runFinalization();
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    });
    thread.start();

    ExecutorService threads = Executors.newFixedThreadPool(2);
    final CyclicBarrier barrier = new CyclicBarrier(2, new Runnable() {

        @Override
        public void run() {
            LOG.trace("Starting threads to send messages!");
        }
    });

    threads.execute(new TestRunner(barrier, latch));
    threads.execute(new TestRunner(barrier, latch));

    latch.await(2, TimeUnit.SECONDS);
    thread.join();

    assertEquals(totalMessagesExpected, numReceived);
}
 
開發者ID:messaginghub,項目名稱:pooled-jms,代碼行數:51,代碼來源:PooledSessionExhaustionBlockTimeoutTest.java


注:本文中的javax.jms.MessageConsumer.receive方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。