【问题标题】:Prevent automatic exit on unsuccessful ActiveMQ reconnect防止 ActiveMQ 重新连接不成功时自动退出
【发布时间】:2020-04-06 01:13:00
【问题描述】:

我设置了一个小型 spring-boot 应用程序,它连接到 ActiveMQ 上的一个或多个主题,这些主题在启动时在应用程序的 application.properties 文件中设置 - 然后将这些消息发送到数据库。

这一切都很好,但是我在尝试实现故障转移时遇到了一些问题 - 基本上,应用程序会尝试重新连接,但在重试一定次数后,应用程序进程将自动退出,阻止重试(理想情况下,我希望应用程序永远重试,直到手动终止或 ActiveMQ 再次可用)。我已尝试将连接 URL(在 application.properties 中使用 url.options)中的连接选项(例如 maxReconnectAttempts)显式设置为 -1/0/99999,但这些似乎都不正确,因为行为是相同的每一次。通过查看Apache's own reference page 上的建议,我也希望这种行为也可以作为默认行为。

如果有人有任何建议强制应用不要退出,我将非常感激!我认为重要的代码如下:

@Configuration
public class AmqConfig {

    private static final Logger LOG = LogManager.getLogger(AmqConfig.class);
    private static final String LOG_PREFIX = "[AmqConfig] ";

    private String clientId;

    private static ArrayList<String> amqUrls = new ArrayList<>();
    private static String amqConnectionUrl;
    private static Integer numSubs;
    private static ArrayList<String> destinations = new ArrayList<>();

    @Autowired
    DatabaseService databaseService;

    public AmqConfig (@Value("${amq.urls}") String[] amqUrl,
                      @Value("${amq.options}") String amqOptions,
                      @Value("${tocCodes}") String[] tocCodes,
                      @Value("${amq.numSubscribers}") Integer numSubs,
                      @Value("${clientId}") String clientId) throws UnknownHostException {

        Arrays.asList(amqUrl).forEach(url -> {
            amqUrls.add("tcp://" + url);
        });

        String amqServerAddress = "failover:(" + String.join(",", amqUrls) + ")";
        String options = Strings.isNullOrEmpty(amqOptions) ? "" : "?" + amqOptions;

        this.amqConnectionUrl = amqServerAddress + options;

        this.numSubs = Optional.ofNullable(numSubs).orElse(4);
        this.clientId = Strings.isNullOrEmpty(clientId) ? InetAddress.getLocalHost().getHostName() : clientId;

        String topic = "Consumer." + this.clientId + ".VirtualTopic.Feed";

        if (tocCodes.length > 0){
            Arrays.asList(tocCodes).forEach(s -> destinations.add(topic + "_" + s));
        } else { // no TOC codes = connecting to default feed
            destinations.add(topic);
        }
    }

    @Bean
    public ActiveMQConnectionFactory connectionFactory() throws JMSException {

        LOG.info("{}Connecting to AMQ at {}", LOG_PREFIX, amqConnectionUrl);
        LOG.info("{}Using client id {}", LOG_PREFIX, clientId);
        ActiveMQConnectionFactory connectionFactory =
                new ActiveMQConnectionFactory(amqConnectionUrl);

        Connection conn = connectionFactory.createConnection();
        conn.setClientID(clientId);
        conn.setExceptionListener(new AmqExceptionListener());
        conn.start();

        destinations.forEach(destinationName -> {
            try {
                for (int i = 0; i < numSubs; i++) {
                    Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
                    Destination destination = session.createQueue(destinationName);
                    MessageConsumer messageConsumer = session.createConsumer(destination);
                    messageConsumer.setMessageListener(new MessageReceiver(databaseService, destinationName));
                }

            } catch (JMSException e) {
                LOG.error("{}Error setting up queue @ {}", LOG_PREFIX, destinationName);
                LOG.error(e.getMessage());
            }
        });

        return connectionFactory;
    }
}


public class MessageReceiver implements MessageListener, ExceptionListener {

     public static final Logger LOG = LogManager.getLogger(MessageReceiver.class);
     private static final String LOG_PREFIX = "[Message Receiver] ";

     private DatabaseService databaseService;

     public MessageReceiver(DatabaseService databaseService, String destinationName){
         this.databaseService = databaseService;
         LOG.info("{}Creating MessageReceiver for queue with destination: {}", LOG_PREFIX, destinationName);
     }

     @Override
     public void onMessage(Message message) {

         String messageText = null;

         if (message instanceof TextMessage) {
             TextMessage tm = (TextMessage) message;
             try {
                 messageText = tm.getText();
             } catch (JMSException e) {
                 LOG.error("{} Error getting message from AMQ", e);
             }
         } else if (message instanceof ActiveMQMessage) {
             messageText = message.toString();
         } else {
             LOG.warn("{}Unrecognised message type, cannot process", LOG_PREFIX);
             LOG.warn(message.toString());
         }

         try {
             databaseService.sendMessageNoResponse(messageText);
         } catch (Exception e) {
             LOG.error("{}Unable to acknowledge message from AMQ. Message: {}", LOG_PREFIX, messageText, e);
         }
     }
}

 public class AmqExceptionListener implements ExceptionListener {

     public static final Logger LOG = LogManager.getLogger(AmqExceptionListener.class);
     private static final String LOG_PREFIX = "[AmqExceptionListener ] ";

     @Override
     public void onException(JMSException e){
         LOG.error("{}Exception thrown by ActiveMQ", LOG_PREFIX, e);
     }
 }

我从我的应用程序中得到的控制台输出如下所示(抱歉,因为它没有太多内容)

[2019-12-12 14:43:30.292] [WARN ] Transport (tcp://[address]:61616) failed , attempting to automatically reconnect: java.io.EOFException
[2019-12-12 14:43:51.098] [WARN ] Failed to connect to [tcp://[address]:61616] after: 10 attempt(s) continuing to retry.

Process finished with exit code 0

【问题讨论】:

  • 您的应用程序是否正确启动,或者您在应用程序启动时遇到此问题?或者当某个节点出现故障时?
  • 如果应用程序启动时 ActiveMQ 已启动,则它可以正常工作。如果它关闭,则应用程序将无法启动,并将为用户记录下来。我正在努力为启动正常但 ActiveMQ 在运行时出现故障的应用程序获取某种形式的故障转移。

标签: java spring-boot activemq spring-jms failover


【解决方案1】:

非常有趣的问题!

配置maxReconnectAttempts=-1会导致连接尝试永远重试,但是我觉得这里的问题如下:

  1. 您在 App 中创建 Bean 时尝试连接到 ActiveMQ startup, 如果在 APP 启动时 ActiveMQ 没有运行,则 Bean 创建将永远重试连接尝试,从而导致 超时,不让APP启动。
  2. 此外,当 ActiveMQ 中途停止运行时,您不会重新尝试连接,因为它是在 @Bean 内部完成的,并且只会在 APP 启动时发生

因此连接不应该在创建 Bean 时发生,但也许可以在 APP 启动后完成(可能在 @PostConstruct 块内)

这些只是指针,你需要继续前进

希望这会有所帮助!

祝你好运!

【讨论】:

    猜你喜欢
    • 2011-04-14
    • 2011-08-20
    • 2016-01-29
    • 2012-07-26
    • 1970-01-01
    • 2011-07-01
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多