我试图捕获由于代理关闭而无法建立的ActiveMQ连接的异常。
使用以下代码:
String url = ActiveMQConnection.DEFAULT_BROKER_URL;
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
Connection connection = connectionFactory.createConnection();
connection.start();
如果代理关闭,则连接到代理的尝试将进入无限循环。如果我将网址更改为
String url = "failover:(tcp://127.0.0.1:61616/)?startupMaxReconnectAttempts=2";
它尝试2次,然后引发异常。(这是我想要的。)
现在,如果我使用带有以下内容的Spring Bean初始化连接对象:
<bean id="jmsFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL">
<!--<value>tcp://0.0.0.0:61616</value>-->
<value>failover:(tcp://127.0.0.1:61616/)?startupMaxReconnectAttempts=2</value>
</property>
</bean>
我在两次尝试中均未连接失败,但收到一条错误消息,但每5秒钟仍会尝试再次连接,再次给出相同的错误消息并无限循环。
ERROR transport.failover.FailoverTransport - Failed to connect to [tcp://127.0.0.1:61616/] after: 2 attempt(s)
WARN jms.listener.DefaultMessageListenerContainer - Could not refresh JMS Connection for destination 'destinationQueue' - retrying in 5000 ms. Cause: Connection refused
ERROR transport.failover.FailoverTransport - Failed to connect to [tcp://127.0.0.1:61616/] after: 2 attempt(s)
WARN jms.listener.DefaultMessageListenerContainer - Could not refresh JMS Connection for destination 'destinationQueue' - retrying in 5000 ms. Cause: Connection refused
ERROR transport.failover.FailoverTransport - Failed to connect to [tcp://127.0.0.1:61616/] after: 2 attempt(s)
WARN jms.listener.DefaultMessageListenerContainer - Could not refresh JMS Connection for destination 'destinationQueue' - retrying in 5000 ms. Cause: Connection refused
ERROR transport.failover.FailoverTransport - Failed to connect to [tcp://127.0.0.1:61616/] after: 2 attempt(s)
WARN jms.listener.DefaultMessageListenerContainer - Could not refresh JMS Connection for destination 'destinationQueue' - retrying in 5000 ms. Cause: Connection refused
these messages repeat!!
我想知道如何在失败的情况下停止这种无限轮询并捕获异常(可能使用PostInit)。
最佳答案
您可以在侦听器类中实现ExceptionListener,并覆盖onException消息。在那里您可以处理通知逻辑。它尝试自动重新连接。
public class QueueListener implements MessageListener,ExceptionListener{
public void onMessage(Message message) {
}
public void onException(JMSException jsme) {
// Send my notifcation here.
}
}