Due to server upgrades, server restarts, network jitter, etc., the network connection between the server and the client may be disconnected. This section describes how to configure connection and topology auto-recovery on the client, so that they can be automatically restored after network connections are disconnected to prevent the service from being affected by disconnections.
Possible Reason
The reasons for triggering connection auto-recovery are as follows:
l I/O of Connection throws an exception.
l Socket read operation timed out.
l Loss of server-side heartbeat detected.
Recovery Method
Java clients of version 4.0.0 or later enable connection and topology auto-recovery by default.
The method to enable connection and topology auto-recovery (Queue, Exchange, Binding, Consumer) on the client is as follows:
l factory.setAutomaticRecoveryEnabled(boolean): Used to enable or disable connection auto-recovery.
l factory.setNetworkRecoveryInterval(long): Used to set the retry interval. If the connection auto-recovery is abnormal, the client with connection auto-recovery set will retry after a fixed time interval (default to 5 seconds).
l factory.setTopologyRecoveryEnabled(boolean): Used to enable topology auto-recovery. Topology includes Queue, Exchange, Binding, and Consumer.
Sample Code
The client sample code to enable connection and topology auto-recovery is as follows:
ConnectionFactory factory = new ConnectionFactory();
// Set the access point and get it on the instance details page of the DMS RabbitMQ console.
factory.setHost("192.168.x.x");
// Set the Vhost name
factory.setVirtualHost("/");
// Port
factory.setPort(5672);
// Set a reasonable timeout based on the network environment.
factory.setConnectionTimeout(30 * 1000);
factory.setHandshakeTimeout(30 * 1000);
factory.setShutdownTimeout(0);
// Enable connection auto-recovery.
factory.setAutomaticRecoveryEnabled(true);
// Set the connection retry interval to 10 seconds.
factory.setNetworkRecoveryInterval(10000);
// Enable topology auto-recovery.
factory.setTopologyRecoveryEnabled(true);
Connection connection = factory.newConnection();Recovery Restriction
The restrictions for connection auto-recovery are as follows:
l Connection disconnected takes some time to detect. To ensure that messages sent during this period are not lost, you should use Publisher Confirms to achieve reliable delivery.
l If the Connection is disconnected due to a channel exception, Connection auto-recovery will not be triggered. Channel exceptions are usually application-level issues that need to be handled by the user.
l Connection auto-recovery does not cause the channel to auto-recovery as well.