Create JMS MessageProducer - Java Message

Java examples for Message:JMS

Description

Create JMS MessageProducer

Demo Code


import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Producer {

  private static Logger logger = LoggerFactory.getLogger(Producer.class);

  public static void main(String[] args) {
    ActiveMQConnectionFactory connectionFactory = null;
    QueueConnection connection = null;/*from   w w  w.ja v a2  s .  c o  m*/

    try {
      connectionFactory = new ActiveMQConnectionFactory(
          "failover:(nio://10.10.16.164:61617,nio://10.10.16.164:31617)?randomize=false");
      connection = connectionFactory.createQueueConnection();
      connection.start();
      QueueSession session = connection.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);
      Queue destination = session.createQueue("activemq.test.queue");
      MessageProducer producer = session.createProducer(destination);
      producer.setDeliveryMode(DeliveryMode.PERSISTENT);

      for (int i = 1; i <= 1000000; i++) {
        String message = i + " activemq.test.queue msg";
        sendMessage(session, producer, message);
      }
      producer.close();
      session.close();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        connection.close();
      } catch (JMSException e) {
        e.printStackTrace();
      }
    }

  }

  public static void sendMessage(Session session, MessageProducer producer, String message) {
    try {
      TextMessage textMessage = session.createTextMessage(message);
      producer.send(textMessage);
      session.commit();
      logger.info(message);
    } catch (Exception e) {
      logger.error("sendMessage error", e);
      sendMessage(session, producer, message);
    }
  }

}

Related Tutorials