用于 Spring Bean 初始化的 ActiveMQ 连接故障转移检测



我正在尝试捕获由于代理关闭而无法建立的 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>
我收到一条错误消息,提示在

2 次尝试中连接失败,但随后,它仍然在每 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.
}

}

最新更新