Help Center> Distributed Message Service for RabbitMQ> Best Practices> Automatic Recovery from Network Exceptions
Updated on 2023-07-17 GMT+08:00

Automatic Recovery from Network Exceptions

This topic describes how to configure automatic network recovery on a client when it is disconnected from the server due to server restart or network jitter. Java clients of version 4.0.0 or later support automatic network recovery by default.

If an application uses the Connection.Close method to close a connection, automatic network recovery will not be enabled or triggered.

Scenarios

Automatic network recovery is triggered in the following scenarios:

  • An exception is thrown in a connection's I/O loop.
  • Socket read times out.
  • Server heartbeat is lost.

Sample Code for Reconnection

If the initial connection between the client and server fails, automatic recovery is not triggered. You are advised to edit the corresponding application code and retry the connection to solve the problem.

The following example shows how to use a Java client to resolve an initial connection failure by retrying a connection.

ConnectionFactory factory = new ConnectionFactory();
// enable automatic recovery if using RabbitMQ Java client library prior to version 4.0.0.
factory.setAutomaticRecoveryEnabled(true);
// configure various connection settings
 
try {
  Connection conn = factory.newConnection();
} catch (java.net.ConnectException e) {
  Thread.sleep(5000);
  // apply retry logic
}