activemq-queue-MessageListener

其他相关文章:
[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...");
}
}
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值