Send JMS topic - Java Message

Java examples for Message:JMS

Description

Send JMS topic

Demo Code



import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;

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

public class SendTopic
{
  public static void main(String[] args) throws JMSException
  {//w  w  w .  j  a  v a  2 s  .  co m
    TopicConnection connection = null;
    TopicSession session = null;
    try
    {
      TopicConnectionFactory factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, "tcp://localhost:61616");
      connection = factory.createTopicConnection();
      connection.start();

      session = connection.createTopicSession(true, Session.AUTO_ACKNOWLEDGE);
      Topic topic = session.createTopic("com.balintimes.Topic");
      TopicPublisher publisher = session.createPublisher(topic);
      
      publisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
      
      sendMessage(session, publisher);

      session.commit();

    }
    catch (Exception e)
    {
      // TODO: handle exception
    }
    finally
    {
      if (session != null)
      {
        session.close();
      }
      if (connection != null)
      {
        connection.close();
      }
    }

  }

  public static void sendMessage(TopicSession session, TopicPublisher publisher) throws Exception
  {

    DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    for (int i = 0; i < 5; i++)
    {

      String message = "message " + (i + 1) + " hi";
      MapMessage map = session.createMapMessage();
      map.setString("text", message);
      map.setString("time", dFormat.format(new Date()));      
      System.out.println(map);
      publisher.send(map);
      Thread.sleep(1 * 1000);
    }
  }
}

Related Tutorials