其他相关文章:
[url]http://wangxinchun.iteye.com/blog/2145998[/url]
[url]http://wangxinchun.iteye.com/blog/2145958[/url]
activemq 中消费者获取消息有两种方式:
1、通过MessageConsumer.receive(TIMEOUT) 方法拉消息。
2、通过MessageConsumer.setMessageListener(new MessageListener(){}) 监听消息。
上面的文章都是用的第一种拉消息的方式,在项目中,更方便的做法是第二种,通过设置消息监听器监听消息,由mq broker 推消息过来。
下面的代码演示了监听方式的用法:
[url]http://wangxinchun.iteye.com/blog/2145998[/url]
[url]http://wangxinchun.iteye.com/blog/2145958[/url]
activemq 中消费者获取消息有两种方式:
1、通过MessageConsumer.receive(TIMEOUT) 方法拉消息。
2、通过MessageConsumer.setMessageListener(new MessageListener(){}) 监听消息。
上面的文章都是用的第一种拉消息的方式,在项目中,更方便的做法是第二种,通过设置消息监听器监听消息,由mq broker 推消息过来。
下面的代码演示了监听方式的用法:
public class Consumer {
private static final String BROKER_URL = "tcp://localhost:61616";
private static final Boolean NON_TRANSACTED = false;
private static final long TIMEOUT = 20000;
public static void main(String[] args) {
String url = BROKER_URL;
if (args.length > 0) {
url = args[0].trim();
}
System.out.println("\nWaiting to receive messages... will timeout after " + TIMEOUT / 1000 +"s");
//MQ 连接工厂对象
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", url);
Connection connection = null;
try {
//建连接
connection = connectionFactory.createConnection();
connection.start();
//创建会话
Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue("test-queue");
MessageConsumer consumer = session.createConsumer(destination);
consumer.setMessageListener(new MessageListener(){
@Override
public void onMessage(Message message) {
if(message instanceof TextMessage){
try {
System.out.println(((TextMessage)message).getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
});
System.in.read();
session.close();
} catch (Exception e) {
System.out.println("Caught exception!");
}
finally {
if (connection != null) {
try {
connection.close();
} catch (JMSException e) {
System.out.println("Could not close an open connection...");
}
}
}
}
}