【问题标题】:How to know when connection to a JMS Topic is lost?如何知道与 JMS 主题的连接何时丢失?
【发布时间】:2016-06-15 18:19:45
【问题描述】:

我有一个 Java 富客户端应用程序,它在启动时在远程 HornetQ JMS 主题上注册一个持久订阅。 但是,如果服务器重新启动,连接就会丢失,只能通过重新启动客户端应用程序来恢复。 这会导致无法接收到 JMS 消息并且在客户端重新启动后一次接收到大量消息的混乱情况。

恢复连接的一个简单解决方案是运行一个计时器来定期检查连接是否仍然有效,否则尝试重新连接。 或者,服务器可以向客户端发送心跳,如果在一段时间后没有收到心跳,则尝试重新连接(如 answer 中提到的)。

但这两种方法似乎都是解决这个问题的笨拙方法,因此我想知道是否有更好的解决方案来找出连接不再可用?

【问题讨论】:

    标签: java hornetq jms-topic


    【解决方案1】:

    要在断开连接时收到通知,您必须在开始连接之前在您的 TopicConnection 上注册一个 ExceptionListener

    private void subscribe() throws JMSException {
    
        // get context / create connection and session / etc.
        TopicConnection connection = ...
    
        connection.setExceptionListener(this::handleExceptions);
        connection.start();
    }
    

    ExceptionListener中可以查看收到的JMSException的错误码。 (错误代码是特定于供应商的)
    在 HornetQ 的情况下,连接丢失后会收到错误代码 DISCONNECT

    private static final String HORNETQ_DISCONNECT_ERROR_CODE = "DISCONNECT";
    
    private void handleExceptions(final JMSException jmsException) {
    
        final String errorCode = jmsException.getErrorCode();
        if (HORNETQ_DISCONNECT_ERROR_CODE.equals(errorCode)) {
            tryConnect();
        }
    }
    

    然后您可以启动一个自动取消计时器,它会尝试每 x 秒重新连接一次,直到成功。

    private static final long SUBSCRIBE_RETRY_TIME_OUT_IN_MILLIS = 60000;
    
    private void tryConnect() {
    
        final Timer timer = new Timer("JMS-Topic-Reconnection-Timer", true);
        final TimerTask timerTask = new TimerTask() {
    
            @Override
            public void run() {
                try {
                    subscribe();
                    // cancel the timer, after the subscription succeeds
                    timer.cancel();
                }
                catch (final Exception e) {
                    logger.info("reconnect to jms topic failed: {}", e.getMessage());
                }
            }
        };
        timer.schedule(timerTask, SUBSCRIBE_RETRY_TIME_OUT_IN_MILLIS, SUBSCRIBE_RETRY_TIME_OUT_IN_MILLIS);
    }
    

    【讨论】:

      猜你喜欢
      • 2014-01-03
      • 2016-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-07
      • 1970-01-01
      • 1970-01-01
      • 2021-07-09
      相关资源
      最近更新 更多