天天看點

JMS 向 actioveMQ 發送消息

public class ProducerTool {

 private Destination destination;

 private int messageCount = 10;

 private long sleepTime = 0L;

 private boolean verbose = true;

 private int messageSize = 255;

 private long timeToLive;

 private String user = ActiveMQConnection.DEFAULT_BROKER_URL;

 private String password = ActiveMQConnection.DEFAULT_PASSWORD;

 private String url = "tcp://localhost:61616" ;//ActiveMQConnection.DEFAULT_BROKER_URL;

 private String subject = "MyTopic" ;//"TOOL.DEFAULT";

 private boolean topic =  true ;    //false;

 private boolean transacted = true;  //false;

 private boolean persistent = true;  //false;

 public static void main(String[] args) {

  ProducerTool producerTool = new ProducerTool();

  String messageText ="這裡設定你要發送的内容" ;

  String []s = messageText.split(".");

     producerTool.sendMessage(messageText);

 }

 public void sendMessage(String messageText) {

  Connection connection=null;

  try {

   if (timeToLive != 0) {

    System.out.println("Messages time to live " + timeToLive + " ms");

   }

   // Create the connection.

   //建立跟 jms 連接配接, 使用者名, 密碼, 連接配接的位址上面已經定義好了!

   ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);   

   connection = connectionFactory.createConnection();

   connection.start();

   // Create the session

   //建立 session, 傳入指定的參數

   Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);

   //System.out.println("session=" + session ) ;

   // 點對點的模式(還有RSS模式)

   if (topic) {

    destination = session.createTopic(subject);

    //System.out.println("destination=" + destination) ;

   } else {

    destination = session.createQueue(subject);

   }

   // Create the producer.

   // 建立生産者

   MessageProducer producer = session.createProducer(destination);

   //System.out.println("producer=" + producer) ;

   if (persistent) {

    producer.setDeliveryMode(DeliveryMode.PERSISTENT);

   } else {

    producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

   }   

   if (timeToLive != 0)

    producer.setTimeToLive(timeToLive);

   // Start sending messages

   //向伺服器發送消息

   TextMessage message = session.createTextMessage(messageText);

   producer.send(message);

   if (transacted) {

    session.commit();  //進行類似的送出

   }

   System.out.println("發送完畢.");

   // Use the ActiveMQConnection interface to dump the connection stats.

   ActiveMQConnection c = (ActiveMQConnection) connection;

   c.getConnectionStats().dump(new IndentPrinter());

  } catch (Exception e) {

   System.out.println("出錯:----------------------");

   System.out.println("Caught: " + e);

   e.printStackTrace();

  } finally {

   try {

    connection.close();

   } catch (Throwable ignore) {

   }

  }

 }

 }