如何使用 Spring AMQP 设置最大连接重试次数

how to set maximum number of connection retries with Spring AMQP

我有一个场景,我的 rabbit mq 实例并不总是可用,我想设置连接重试的最大次数,这可以用 amqp 实现吗?

示例,

@Bean
public ConnectionFactory connectionFactory() {
  CachingConnectionFactory factory = new CachingConnectionFactory();
  factory.setUri("amqprl//");
  factory ../ try uri connection for 4 times max then fail if still no connection
  return factory;
}

消息生产者只会在您发送消息时尝试创建连接。

消息消费者(容器工厂)将无限期重试。

您可以添加一个 ConnectionListener 到连接工厂和 stop() 监听器容器,在一些失败之后。

@FunctionalInterface
public interface ConnectionListener {

    /**
     * Called when a new connection is established.
     * @param connection the connection.
     */
    void onCreate(Connection connection);

    /**
     * Called when a connection is closed.
     * @param connection the connection.
     * @see #onShutDown(ShutdownSignalException)
     */
    default void onClose(Connection connection) {
    }

    /**
     * Called when a connection is force closed.
     * @param signal the shut down signal.
     * @since 2.0
     */
    default void onShutDown(ShutdownSignalException signal) {
    }

    /**
     * Called when a connection couldn't be established.
     * @param exception the exception thrown.
     * @since 2.2.17
     */
    default void onFailed(Exception exception) {
    }

}