如何暂停和恢复JMS消息的异步使用

时间:2016-09-19 11:08:56

标签: java jms activemq jms-topic activemq-artemis

我使用activeMQ构建一个应用程序,我有一个生产者和一个消费者。          在消费者iam中,使用MessageListener异步监听来自生产者的消息,这是使用名为onMessage(消息消息)的方法完成的。          但在使用消息之前,我想执行条件检查,然后使用消息。          我不想使用同步消息,因为它会违反我的设计。

dump()

检查条件,例如检测互联网连接等

  void initialize() throws JMSException {
            this.connection = this.connectionFactory.createConnection();
            this.connection.start();
            final Session session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            final Destination destination = session.createQueue("testQ");
            this.consumer = session.createConsumer(destination);
            this.consumer.setMessageListener(this);
}

任何代码示例都会很棒。

2 个答案:

答案 0 :(得分:1)

您不清楚为什么要进行检查,因为如果连接有任何问题,那么您的应用程序会收到此类错误的通知。您可以为JMS连接设置ExceptionListener,如果连接出现问题,将调用它。

如果存在连接问题,则不会调用onMessage。

在设置消费者的消息监听器之后,我也会推送connection.start()方法调用。 connection.start()调用向消息传递提供程序指示应用程序已准备好接收消息。

有connection.stop()来暂停/停止消息传递。您可以再次发出connection.start()以恢复邮件传递。

根据您的回复进行更新

我建议您使用具有客户端确认模式的会话。

final Session session = this.connection.createSession(false, Session.CLIENT_ACKNOWLEDGE)

然后在onMessage方法中,如果没有互联网连接,请不要确认该消息。如果消息尚未过期,将再次发送该消息。

答案 1 :(得分:1)

在异步消息传递中,您始终可以在处理消息之前检查条件。一旦在您的监听器代码(即OnMessage方法)上收到JMS消息,您就可以给出进一步的指示。我已经解决了这个问题,我想用我的数据库内容检查JMS消息。

通过将urlConnection设置为webservice url来检查互联网连接是否存在,如下所示:

  public static boolean isReachable(String targetUrl) throws IOException
{
   try {
     HttpURLConnection httpUrlConnection = (HttpURLConnection) new URL(
        targetUrl).openConnection();
    httpUrlConnection.setRequestMethod("HEAD");


    int responseCode = httpUrlConnection.getResponseCode();

    return responseCode == HttpURLConnection.HTTP_OK;
} catch (UnknownHostException noInternetConnection)
  {
    return false;
   }
}

然后在你的onMessage方法中将方法调用为

public void onMessage(final Message message) {
    if(isReachable){
    Preconditions.checkNotNull(message);

    if (!(message instanceof TextMessage)) {
        _LOG.error("The message is not of type TextMessage but of type {} so we could not process", message.getClass().getSimpleName());
        throw new IllegalArgumentException("This type '" + message.getClass().getSimpleName() + "' of message could not been handled");
    }

    try {
        final String messageType = message.getStringProperty("messageType");
        Preconditions.checkNotNull(messageType);
        _LOG.info("The MessageType is {}", messageType);

        final String msg = ((TextMessage) message).getText();
        Preconditions.checkNotNull(msg);
        _LOG.debug(msg);

        process(messageType, msg);
    } catch (final JMSException e) {
        _LOG.error("We could not read the message", e);
    }
  }
}