Posted on 2009-10-30 14:24
Robin 閱讀(328)
評論(0) 編輯 收藏
在下面的例子中,分別發送一個Persistent和nonpersistent的消息,然后關閉退出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!”時,說明兩個消息都已經發送成功,然后我們結束它,來停止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();
}
}
});
}
}
運行上面的程序,可以得到下面的輸出結果:
Consumer get A persistent Message
可以看出消息消費者只接收到一個消息,它是一個Persistent的消息。而剛才發送的non persistent消息已經丟失了。
另外, 如果發送一個non persistent消息, 而剛好這個時候沒有消費者在監聽, 這個消息也會丟失.