原文地址:http://blog.csdn.net/zhangxs_3/article/details/4034801
我们都知道Queue 即我们经常说的点对点或者生产者/消费者 模型。 生产者将消息发送到队列, 消费者从队列中消费消息,一个消息指能被消费一次。下面例子中启动了两个消费者一个生产者。
public class TestQueue {
private static String brokerURL = "tcp://192.168.2.240:61616";
private static ConnectionFactory connectionFactory;
private static Connection connection;
private static Session session;
private static Destination queue;
static{
connectionFactory = new ActiveMQConnectionFactory(brokerURL);
try {
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
queue = session.createQueue("testqueue");
} catch (JMSException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
MessageProducer producer = session.createProducer(queue);
MessageConsumer consumer1 = session.createConsumer(queue);
MessageConsumer consumer2 = session.createConsumer(queue);
consumer1.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
try {
String content = message.getStringProperty("content");
System.out.println("consumer1:"+content);
} catch (JMSException e) {
e.printStackTrace();
}
}
});
consumer2.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
try {
String content = message.getStringProperty("content");
System.out.println("consumer2:"+content);
} catch (JMSException e) {
e.printStackTrace();
}
}
});
for(int i=0;i<10;i++){
Message message = session.createMessage();
message.setStringProperty("content", i+"");
producer.send(message);
}
}
}
运行结果:
consumer1:0
consumer2:1
consumer1:2
consumer2:3
consumer1:4
consumer2:5
consumer1:6
consumer2:7
consumer1:8
consumer2:9
从结果中我们可以看出,每条消息只能被一个消费者消费,但我们并不能确定到底有哪个消费者消费。