深入掌握JMS(七):DeliveryMode例子
在下面的例子中,分別發(fā)送一個Persistent和nonpersistent的消息,然后關(guān)閉退出JMS。
import javax.jms.Connection; import javax.jms.DeliveryMode; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.command.ActiveMQQueue; public class DeliveryModeSendTest { public static void main(String[] args) throws Exception { ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); Connection connection = factory.createConnection(); connection.start(); Queue queue = new ActiveMQQueue("testQueue"); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(queue); producer.setDeliveryMode(DeliveryMode.PERSISTENT); producer.send(session.createTextMessage("A persistent Message")); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); producer.send(session.createTextMessage("A non persistent Message")); System.out.println("Send messages sucessfully!"); } } 運行上面的程序,當輸出“Send messages sucessfully!”時,說明兩個消息都已經(jīng)發(fā)送成功,然后我們結(jié)束它,來停止JMS Provider。 接下來我們重新啟動JMS Provicer,然后添加一個消費者: import javax.jms.Connection; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageListener; import javax.jms.Queue; import javax.jms.Session; import javax.jms.TextMessage; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.command.ActiveMQQueue; public class DeliveryModeReceiveTest { public static void main(String[] args) throws Exception { ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost"); Connection connection = factory.createConnection(); connection.start(); Queue queue = new ActiveMQQueue("testQueue"); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer comsumer = session.createConsumer(queue); comsumer.setMessageListener(new MessageListener(){ public void onMessage(Message m) { try { System.out.println("Consumer get " + ((TextMessage)m).getText()); } catch (JMSException e) { e.printStackTrace(); } } }); } } 運行上面的程序,可以得到下面的輸出結(jié)果: Consumer get A persistent Message 可以看出消息消費者只接收到一個消息,它是一個Persistent的消息。而剛才發(fā)送的non persistent消息已經(jīng)丟失了。 另外, 如果發(fā)送一個non persistent消息, 而剛好這個時候沒有消費者在監(jiān)聽, 這個消息也會丟失. |
|