activemq-topic-durable

其他参考:
[url]http://wangxinchun.iteye.com/blog/2146172[/url]
[url]http://wangxinchun.iteye.com/blog/2146120[/url]
[url]http://wangxinchun.iteye.com/blog/2145998[/url]
[url]http://wangxinchun.iteye.com/blog/2145958[/url]
[url]http://wangxinchun.iteye.com/blog/2147335[/url]
[b]有这样一种场景,如果Publisher 发布消息是,某一个Subscriber 由于特殊原因,比如断网或在系统死掉,那么希望在这个Subscriber 在重启之后能收到Publisher 在自己挂掉这段时间内的消息[/b]。AMQ 提供了这种功能~

做法:
值需要Subscriber 的 MessageConsumer的生成方式做变动:
MessageConsumer consumer = session.createDurableSubscriber(destination, clientId) ;

对,就是指定clientId ,重启后broker根据clientId发送遗漏的消息,并且这个clientId 不能有冲突,最好使用机器的ip+port+businessID 。

请看下面这个例子:

public class Subscriber implements MessageListener {
private static final String BROKER_URL = "tcp://localhost:61616";
private static final Boolean NON_TRANSACTED = false;
private final CountDownLatch countDownLatch;
public Subscriber(CountDownLatch latch) {
countDownLatch = latch;
}

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... Either waiting for END message or press Ctrl+C to exit");
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", url);
Connection connection = null;
final CountDownLatch latch = new CountDownLatch(1);

try {

connection = connectionFactory.createConnection();
String clientId = System.getProperty("clientId")+"";
connection.setClientID(clientId);

connection.start();

Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
Topic destination = session.createTopic("test-topic");

MessageConsumer consumer = session.createDurableSubscriber(destination, clientId) ;
consumer.setMessageListener(new Subscriber(latch));
latch.await();
consumer.close();
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...");
}
}
}
}

@Override
public void onMessage(Message message) {
try {
if (message instanceof TextMessage) {
String text = ((TextMessage) message).getText();
if ("END".equalsIgnoreCase(text)) {
System.out.println("Received END message!");
countDownLatch.countDown();
}
else {
System.out.println("Received message:" +text);
}
}
} catch (JMSException e) {
System.out.println("Got a JMS Exception!");
}
}
}



[b]验证:[/b]1、启动Subscriber
2、启动Publisher
3、关闭Subscriber
4、使用Publisher 发消息。
5、启动Subscriber 注意:此时Subscriber 收到了消息~
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值