Java examples for Message:JMS
JMS Simple Subscriber
/*/* w ww . ja v a2s . c o m*/ * Copyright (C) Red Hat, Inc. * http://www.redhat.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fusesource.examples.activemq; import javax.jms.*; import javax.naming.Context; import javax.naming.InitialContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class SimpleSubscriber { private static final Log LOG = LogFactory .getLog(SimpleSubscriber.class); private static final Boolean NON_TRANSACTED = false; private static final String CONNECTION_FACTORY_NAME = "myJmsFactory"; private static final int MESSAGE_TIMEOUT_MILLISECONDS = 120000; public static void main(String args[]) { Connection connection = null; try { // JNDI lookup of JMS Connection Factory and JMS Destination Context context = new InitialContext(); ConnectionFactory factory = (ConnectionFactory) context .lookup(CONNECTION_FACTORY_NAME); connection = factory.createConnection(); connection.setClientID("ApplicationA"); connection.start(); Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE); String topicName = System.getProperty("topic"); Topic topic = session.createTopic(topicName); MessageConsumer consumer = session.createConsumer(topic); LOG.info("Start consuming messages from " + topicName + " with " + MESSAGE_TIMEOUT_MILLISECONDS + "ms timeout"); // Synchronous message consumer int i = 1; while (true) { Message message = consumer .receive(MESSAGE_TIMEOUT_MILLISECONDS); if (message != null) { if (message instanceof TextMessage) { String text = ((TextMessage) message).getText(); LOG.info("Got " + (i++) + ". message: " + text); } } else { break; } } consumer.close(); session.close(); } catch (Throwable t) { LOG.error(t); } finally { // Cleanup code // In general, you should always close producers, consumers, // sessions, and connections in reverse order of creation. // For this simple example, a JMS connection.close will // clean up all other resources. if (connection != null) { try { connection.close(); } catch (JMSException e) { LOG.error(e); } } } } }