Search code examples
javajmsqpid

JMS QPID handle reconnect


I'm using JMS with QPID and wondering how to configure a reconnect if the broker cannot be reached anymore:

try (Connection connection = jmsFactory.createConnection(); Session session = connection.createSession()) {
            Queue queue = session.createQueue("queue:testQueue");
            Topic topic = session.createTopic("topic:testTopic");
            TextMessage message = session.createTextMessage("toQueue");
            TextMessage message2 = session.createTextMessage("toTopic");

            MessageProducer producer = session.createProducer(queue);
            producer.send(message);
            MessageProducer producer2 = session.createProducer(topic);
            producer2.send(message2);
            MessageConsumer consumer = session.createConsumer(queue);
            consumer.setMessageListener(new MessageListener() {

                @Override
                public void onMessage(Message message) {
                    try {
                        String content = extractBody(message);
                        System.out.println("From: " + message.getJMSDestination() + " Content: " + content);
                        message.acknowledge();
                    } catch (JMSException e) {
                        System.out.println("CANNOT GET CONTENT= " + e);
                    }
                }
            });
            connection.start();
            consumer.close();
  }catch ...

If the broker is not reachable anymore I would like to reconnect until the broker is back up again.


Solution

  • If you are referring to Qpid JMS then the client provides a failover transport that handles automatic reconnection for you so that your code wouldn't need to do anything. The documentation explains how to configure this, basically you modify your URI to wrap the host information with the failover tag:

     failover:(amqp://123.0.0.123:5672)