深入掌握JMS(七):DeliveryMode例子

        在下面的例子中,分别发送一个Persistent和nonpersistent的消息,然后关闭退出JMS。

package com.bijian.study;

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("tcp://localhost:61616");
		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!");
		
		connection.close();
	}
}

        运行上面的程序,当输出“Send messages sucessfully!”时,说明两个消息都已经发送成功,然后我们结束它,来停止JMS Provider,在这里即是关闭ActiveMQ服务。

        接下来我们重新启动JMS Provicer,在这里即是重新start ActiveMQ,然后添加一个消费者:

package com.bijian.study;

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("tcp://localhost:61616");
		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消息已经丢失了。

        而不管发送的是不是persistent消息,也不管这个时候没有消费者在监听,消息都不会丢失,除非设了producer.setTimeToLive(设置存活时间);且超过了设置的存活时间,且消息就丢失了,但此时不管是不是persistent消息都会丢失。

文章来源:http://www.cnblogs.com/guthing/archive/2010/06/12/1757162.html

猜你喜欢

转载自bijian1013.iteye.com/blog/2311686
今日推荐