Receive JMS topic - Java Message

Java examples for Message:JMS

Description

Receive JMS topic

Demo Code



import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class ReceiverTopic
{
  public static void main(String[] args) throws JMSException
  {/*w  w w .  j a v  a2  s  . c o m*/

    TopicConnection connection = null;

    TopicSession session = null;

    try
    {
      TopicConnectionFactory factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, "tcp://172.16.0.191:61616");
      connection = factory.createTopicConnection();
      connection.setClientID("com.balintimes.topicClientID");
      
      connection.start();
      session = connection.createTopicSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
      
      Topic topic = session.createTopic("com.balintimes.Topic");
      TopicSubscriber subscriber = session.createSubscriber(topic);
      
      subscriber.setMessageListener(new MessageListener()
      {
        public void onMessage(Message msg)
        {
          if (msg != null)
          {
            MapMessage map = (MapMessage) msg;
            try
            {
              System.out.println(map.getString("time") + " #" + map.getString("text"));
            }
            catch (JMSException e)
            {
              e.printStackTrace();
            }
          }
        }
      });
      Thread.sleep(1000 * 30); 
      session.commit();
    }
    catch (Exception e)
    {
    }
    finally
    {
      if (session != null)
      {
        session.close();
      }
      if (connection != null)
      {
        connection.close();
      }
    }
  }
}

Related Tutorials