天天看点

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) {

   }

  }

 }

 }