Create JMS Session - Java Message

Java examples for Message:JMS

Description

Create JMS Session

Demo Code

package com.xiaoniuapp.activemq.producer;

import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.QueueConnection;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

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


public class VirtualTopicProducer {

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

  public static void main(String[] args) {
    ActiveMQConnectionFactory connectionFactory = null;
    QueueConnection connection = null;/*from  ww  w . j  av a 2 s .  c  o  m*/

    try {
      connectionFactory = new ActiveMQConnectionFactory(
          "failover:(nio://10.10.16.164:61617,tcp://10.10.16.164:31617)?randomize=false");
      connection = connectionFactory.createQueueConnection();
      connection.start();
      Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
      Topic destination = session.createTopic("VirtualTopic.UserReg");
      MessageProducer producer = session.createProducer(destination);
      producer.setDeliveryMode(DeliveryMode.PERSISTENT);

      for (int i = 1; i <= 100; i++) {
        String message = i + "VirtualTopic.UserReg";
        sendMessage(session, producer, message);
      }
      producer.close();
      session.close();

      Thread.sleep(60000);
    } 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