ActiveMQ学习笔记之十--从队列中接收消息
从队列中接收消息
public static void testReceive() throws Exception {
ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
Connection connection = factory.createConnection();
connection.start();
final Session session = connection.createSession(true/*支持事务*/, Session.AUTO_ACKNOWLEDGE);
Destination queue = session.createQueue("test_123");
MessageConsumer consumer = session.createConsumer(queue);
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
try {
if (message instanceof TextMessage) {
String text = ((TextMessage) message).getText();
session.commit();//如果开启事务,这儿就需要提交,才会消费掉这条消息
System.out.println(text);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
可以观察到队列的变化: