Java Code Examples for com.rabbitmq.client.ConnectionFactory#setAutomaticRecoveryEnabled()

The following examples show how to use com.rabbitmq.client.ConnectionFactory#setAutomaticRecoveryEnabled() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RabbitMQConfiguration.java    From cukes with Apache License 2.0 8 votes vote down vote up
@Bean
@DependsOn("amqpBroker")
CachingConnectionFactory connectionFactory() {
    log.info("Creating connection factory for MQ broker...");
    ConnectionFactory cf = new ConnectionFactory();
    cf.setHost(hostname);
    cf.setPort(port);
    cf.setUsername(userName);
    cf.setPassword(password);
    cf.setVirtualHost(virtualHost);
    cf.setAutomaticRecoveryEnabled(false);
    if (useSSL) {
        try {
            cf.useSslProtocol();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            //TODO don't throw raw exceptions
            throw new RuntimeException(e);
        }
    }

    log.info("Connection factory created.");
    return new CachingConnectionFactory(cf);
}
 
Example 2
Source File: RabbitMQClient.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
public RabbitMQClient(RabbitMQOptions rabbitMQOptions) {
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setUsername(rabbitMQOptions.username);
    connectionFactory.setPassword(rabbitMQOptions.password);
    connectionFactory.setVirtualHost(rabbitMQOptions.virtualHost);
    connectionFactory.setHost(rabbitMQOptions.host);
    connectionFactory.setPort(rabbitMQOptions.port);
    connectionFactory.setSharedExecutor(workers);
    connectionFactory.setAutomaticRecoveryEnabled(true);

    GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
    genericObjectPoolConfig.setMinIdle(8);
    genericObjectPoolConfig.setMaxTotal(18);
    genericObjectPoolConfig.setMinIdle(8);
    pool = new GenericObjectPool<>(new RabbitMQChannelFactory(createConnection(connectionFactory)), genericObjectPoolConfig);
}
 
Example 3
Source File: QueueClient.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
private ConnectionFactory createConnectionFactory() throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(this.config.getUsername());
    factory.setPassword(this.config.getPassword());
    factory.setVirtualHost(this.config.getVirtualHost());

    factory.setAutomaticRecoveryEnabled(true);
    factory.setConnectionTimeout(this.config.getConnectionTimeout());
    factory.setNetworkRecoveryInterval(this.config.getNetworkRecoveryInterval());

    if (this.threadFactory != null) {
        factory.setThreadFactory(this.threadFactory);
    }

    return factory;
}
 
Example 4
Source File: Consumer4FanoutExchange.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	
       ConnectionFactory connectionFactory = new ConnectionFactory() ;
       connectionFactory.setHost(Constant.ip);
       connectionFactory.setPort(Constant.port);
	connectionFactory.setVirtualHost("/");
	
       connectionFactory.setAutomaticRecoveryEnabled(true);
       connectionFactory.setNetworkRecoveryInterval(3000);
       Connection connection = connectionFactory.newConnection();
       
       Channel channel = connection.createChannel();  
	//4 声明
	String exchangeName = "test_fanout_exchange";
	String exchangeType = "fanout";
	String queueName = "test_fanout_queue";
	String routingKey = "";	//不设置路由键
	channel.exchangeDeclare(exchangeName, exchangeType, true, false, false, null);
	channel.queueDeclare(queueName, false, false, false, null);
	channel.queueBind(queueName, exchangeName, routingKey);
	
       //durable 是否持久化消息
       QueueingConsumer consumer = new QueueingConsumer(channel);
       //参数:队列名称、是否自动ACK、Consumer
       channel.basicConsume(queueName, true, consumer); 
       //循环获取消息  
       while(true){  
           //获取消息,如果没有消息,这一步将会一直阻塞  
           Delivery delivery = consumer.nextDelivery();  
           String msg = new String(delivery.getBody());
           System.out.println("收到消息:" + msg);
       } 
}
 
Example 5
Source File: RabbitMQClient_4_x_IT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void testPull_autorecovery() throws Exception {
    ConnectionFactory connectionFactory = getConnectionFactory();
    connectionFactory.setAutomaticRecoveryEnabled(true);

    testRunner.runPullTest();
}
 
Example 6
Source File: RabbitMQClient_3_3_0_to_4_0_0_IT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void testPush() throws Exception {
    ConnectionFactory connectionFactory = getConnectionFactory();
    connectionFactory.setAutomaticRecoveryEnabled(false);

    testRunner.runPushTest();
}
 
Example 7
Source File: RabbitMQClient_4_x_IT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void testPush_nio_autorecovery() throws Exception {
    ConnectionFactory connectionFactory = getConnectionFactory();
    connectionFactory.setAutomaticRecoveryEnabled(true);
    connectionFactory.useNio();

    testRunner.runPushTest();
}
 
Example 8
Source File: RabbitMQClient_5_x_IT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void testPush_autorecovery() throws Exception {
    ConnectionFactory connectionFactory = getConnectionFactory();
    connectionFactory.setAutomaticRecoveryEnabled(true);

    testRunner.runPushTest();
}
 
Example 9
Source File: RabbitMQClient_4_x_IT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void testPush_autorecovery() throws Exception {
    ConnectionFactory connectionFactory = getConnectionFactory();
    connectionFactory.setAutomaticRecoveryEnabled(true);

    testRunner.runPushTest();
}
 
Example 10
Source File: RabbitMQClient_4_x_IT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void testPush() throws Exception {
    ConnectionFactory connectionFactory = getConnectionFactory();
    connectionFactory.setAutomaticRecoveryEnabled(false);

    testRunner.runPushTest();
}
 
Example 11
Source File: RabbitMqIO.java    From beam with Apache License 2.0 5 votes vote down vote up
public ConnectionHandler(String uri)
    throws URISyntaxException, NoSuchAlgorithmException, KeyManagementException {
  connectionFactory = new ConnectionFactory();
  connectionFactory.setUri(uri);
  connectionFactory.setAutomaticRecoveryEnabled(true);
  connectionFactory.setConnectionTimeout(60000);
  connectionFactory.setNetworkRecoveryInterval(5000);
  connectionFactory.setRequestedHeartbeat(60);
  connectionFactory.setTopologyRecoveryEnabled(true);
  connectionFactory.setRequestedChannelMax(0);
  connectionFactory.setRequestedFrameMax(0);
}
 
Example 12
Source File: ConnectionBasedRabbitConnectionFactoryFactory.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public ConnectionFactory createConnectionFactory(final Connection connection,
        final ExceptionHandler exceptionHandler) {
    checkNotNull(connection, "Connection");
    checkNotNull(exceptionHandler, "Exception Handler");

    try {
        final ConnectionFactory connectionFactory = new CustomConnectionFactory();
        if (SECURE_AMQP_SCHEME.equalsIgnoreCase(connection.getProtocol())) {
            if (connection.isValidateCertificates()) {
                final SSLContextCreator sslContextCreator =
                        SSLContextCreator.fromConnection(connection, null);
                connectionFactory.useSslProtocol(sslContextCreator.withoutClientCertificate());
            } else {
                // attention: this accepts all certificates whether they are valid or not
                connectionFactory.useSslProtocol();
            }
        }

        connectionFactory.setUri(connection.getUri());

        // this makes no difference as the used newmotion client always sets the AutomaticRecoveryEnabled to false:
        connectionFactory.setAutomaticRecoveryEnabled(connection.isFailoverEnabled());

        connectionFactory.setExceptionHandler(exceptionHandler);

        configureConnectionFactory(connectionFactory, connection.getSpecificConfig());

        return connectionFactory;
    } catch (final NoSuchAlgorithmException | KeyManagementException | URISyntaxException e) {
        LOGGER.warn(e.getMessage());
        throw new IllegalStateException("Failed to create RabbitMQ connection factory.", e);
    }
}
 
Example 13
Source File: RabbitMQTopicUtil.java    From wangmarket with Apache License 2.0 5 votes vote down vote up
/**
 * 设置RabbitMQ相关信息
 * @param host rabbitMQ所在的ip,如 100.51.15.10
 * @param username rabbitMQ登陆的username,如rabbitMQ安装后默认的账户 guest
 * @param password 登陆密码
 * @param port 端口号,默认为 5672
 */
public RabbitMQTopicUtil(String host, String username, String password, int port) {
	factory = new ConnectionFactory();
	//设置RabbitMQ相关信息
    factory.setHost(host);
    factory.setUsername(username);
    factory.setPassword(password);
    factory.setPort(port);
    factory.setAutomaticRecoveryEnabled(true); //设置网络异常重连
    //factory.setTopologyRecoveryEnabled(true);//设置重新声明交换器,队列等信息。
}
 
Example 14
Source File: RabbitMQClient_5_x_IT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void testPull_nio_autorecovery() throws Exception {
    ConnectionFactory connectionFactory = getConnectionFactory();
    connectionFactory.setAutomaticRecoveryEnabled(true);
    connectionFactory.useNio();

    testRunner.runPullTest();
}
 
Example 15
Source File: RabbitMQClient_3_3_0_to_4_0_0_IT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void testPush_autorecovery() throws Exception {
    ConnectionFactory connectionFactory = getConnectionFactory();
    connectionFactory.setAutomaticRecoveryEnabled(true);

    testRunner.runPushTest();
}
 
Example 16
Source File: RabbitMQClient_3_3_0_to_4_0_0_IT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void testPull_autorecovery() throws Exception {
    ConnectionFactory connectionFactory = getConnectionFactory();
    connectionFactory.setAutomaticRecoveryEnabled(true);

    testRunner.runPullTest();
}
 
Example 17
Source File: Consumer4DirectExchange.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {


        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constant.ip);
        connectionFactory.setPort(Constant.port);
        connectionFactory.setVirtualHost("/");

        connectionFactory.setAutomaticRecoveryEnabled(true);
        connectionFactory.setNetworkRecoveryInterval(3000);
        Connection connection = connectionFactory.newConnection();

        Channel channel = connection.createChannel();
        //4 声明
        String exchangeName = "test_direct_exchange";
        String exchangeType = "direct";
        String queueName = "test_direct_queue";
        String routingKey = "test.direct";

        //表示声明了一个交换机
        channel.exchangeDeclare(exchangeName, exchangeType, true, false, false, null);
        //表示声明了一个队列
        channel.queueDeclare(queueName, false, false, false, null);
        //建立一个绑定关系:
        channel.queueBind(queueName, exchangeName, routingKey);

        //durable 是否持久化消息
        QueueingConsumer consumer = new QueueingConsumer(channel);
        //参数:队列名称、是否自动ACK、Consumer
        channel.basicConsume(queueName, true, consumer);
        //循环获取消息  
        while (true) {
            //获取消息,如果没有消息,这一步将会一直阻塞  
            Delivery delivery = consumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.out.println("收到消息:" + msg);
        }
    }
 
Example 18
Source File: DefaultChannelFactory.java    From rxrabbit with MIT License 4 votes vote down vote up
private synchronized Connection createConnection(ChannelType connectionType) throws ConnectionFailureException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date startTime = new Date();
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    settings.getClient_properties().put("connection_type", connectionType.toString());
    settings.getClient_properties().put("connect_time", sdf.format(startTime)+"Z");

    ConnectionFactory cf = new ConnectionFactory();
    cf.setRequestedHeartbeat(settings.getHeartbeat());
    cf.setConnectionTimeout(settings.getConnection_timeout_millis());
    cf.setShutdownTimeout(settings.getShutdown_timeout_millis());
    cf.setRequestedFrameMax(settings.getFrame_max());
    cf.setHandshakeTimeout(settings.getHandshake_timeout_millis());
    cf.setClientProperties((Map)settings.getClient_properties());
    //cf.setSocketConfigurator(); NOTE is this worth investigating??
    cf.setRequestedChannelMax(0);//Hard coded ..
    cf.setAutomaticRecoveryEnabled(false);//Hard coded ..
    cf.setTopologyRecoveryEnabled(false);//Hard coded ..

    Exception lastException = null;
    Connection connection = null;
    for (BrokerAddresses.BrokerAddress address : addresses) {
        cf.setPassword(address.password);
        cf.setUsername(address.username);
        cf.setPort(address.port);
        cf.setHost(address.host);
        cf.setVirtualHost(address.virtualHost);
        try {
            if(address.scheme.toLowerCase().equals("amqps")){
                cf.useSslProtocol();
                cf.setSocketFactory(SSLSocketFactory.getDefault()); //Because rabbit uses NoopTrustStore by default...
            }
            log.infoWithParams("Creating "+connectionType+" connection to broker ...",
                    "address", address.toString(),
                    "settings", settings.toString());
            connection = cf.newConnection();
            boolean isOpen = connection.isOpen();
            if(!isOpen){
                continue;
            }
            break;
        } catch (Exception e) {
            log.debugWithParams("Failed to createConnection to broker",
                    "address", address.toString());
            lastException = e;
        }
    }

    if(connection == null){
        throw new ConnectionFailureException(cf, lastException);
    }

    conToChannel.put(connectionType,
            new ConnectionInfo(
                    connection,
                    new ArrayList<ChannelImpl>(),
                    settings.getClient_properties(),
                    connectionType)
    );
    log.infoWithParams("Successfully created "+connectionType+" connection to broker.",
            "address", addresses.get(0).toString(),
            "localPort", ((AMQConnection) connection).getLocalPort(),
            "settings", settings.toString());

    return connection;

}
 
Example 19
Source File: RabbitMQConnectionFactory.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
/**
 * Initiate rabbitmq connection factory from the connection parameters
 *
 * @param parameters connection parameters
 */
private void initConnectionFactory(Map<String, String> parameters) throws RabbitMQException {
    String hostnames = StringUtils.defaultIfEmpty(
            parameters.get(RabbitMQConstants.SERVER_HOST_NAME), ConnectionFactory.DEFAULT_HOST);
    String ports = StringUtils.defaultIfEmpty(
            parameters.get(RabbitMQConstants.SERVER_PORT), String.valueOf(ConnectionFactory.DEFAULT_AMQP_PORT));
    String username = StringUtils.defaultIfEmpty(
            parameters.get(RabbitMQConstants.SERVER_USER_NAME), ConnectionFactory.DEFAULT_USER);
    String password = StringUtils.defaultIfEmpty(
            parameters.get(RabbitMQConstants.SERVER_PASSWORD), ConnectionFactory.DEFAULT_PASS);
    String virtualHost = StringUtils.defaultIfEmpty(
            parameters.get(RabbitMQConstants.SERVER_VIRTUAL_HOST), ConnectionFactory.DEFAULT_VHOST);
    int heartbeat = NumberUtils.toInt(
            parameters.get(RabbitMQConstants.HEARTBEAT), ConnectionFactory.DEFAULT_HEARTBEAT);
    int connectionTimeout = NumberUtils.toInt(
            parameters.get(RabbitMQConstants.CONNECTION_TIMEOUT), ConnectionFactory.DEFAULT_CONNECTION_TIMEOUT);
    long networkRecoveryInterval = NumberUtils.toLong(
            parameters.get(RabbitMQConstants.NETWORK_RECOVERY_INTERVAL), ConnectionFactory.DEFAULT_NETWORK_RECOVERY_INTERVAL);
    this.retryInterval = NumberUtils.toInt(
            parameters.get(RabbitMQConstants.RETRY_INTERVAL), RabbitMQConstants.DEFAULT_RETRY_INTERVAL);
    this.retryCount = NumberUtils.toInt(
            parameters.get(RabbitMQConstants.RETRY_COUNT), RabbitMQConstants.DEFAULT_RETRY_COUNT);
    boolean sslEnabled = BooleanUtils.toBooleanDefaultIfNull(
            BooleanUtils.toBoolean(parameters.get(RabbitMQConstants.SSL_ENABLED)), false);

    String[] hostnameArray = hostnames.split(",");
    String[] portArray = ports.split(",");
    if (hostnameArray.length == portArray.length) {
        addresses = new Address[hostnameArray.length];
        for (int i = 0; i < hostnameArray.length; i++) {
            try {
                addresses[i] = new Address(hostnameArray[i].trim(), Integer.parseInt(portArray[i].trim()));
            } catch (NumberFormatException e) {
                throw new RabbitMQException("Number format error in port number", e);
            }
        }
    } else {
        throw new RabbitMQException("The number of hostnames must be equal to the number of ports");
    }

    connectionFactory = new ConnectionFactory();
    connectionFactory.setUsername(username);
    connectionFactory.setPassword(password);
    connectionFactory.setVirtualHost(virtualHost);
    connectionFactory.setRequestedHeartbeat(heartbeat);
    connectionFactory.setConnectionTimeout(connectionTimeout);
    connectionFactory.setNetworkRecoveryInterval(networkRecoveryInterval);
    connectionFactory.setAutomaticRecoveryEnabled(true);
    connectionFactory.setTopologyRecoveryEnabled(true);
    setSSL(parameters, sslEnabled);
}
 
Example 20
Source File: ConnectionOptions.java    From lyra with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a rabbitmq-java connection factory instance with automatic recovery turned off by default.
 * This is necessary as rabbitmq-java > 4.0.0 enables it by default, resulting in two restored consumer in case of
 * connection resets.
 *
 * @return a com.rabbitmq.client.ConnectionFactory with automatic recovery disabled
 */
private ConnectionFactory makeConnectionFactory() {
  ConnectionFactory factory = new ConnectionFactory();
  factory.setAutomaticRecoveryEnabled(false);
  return factory;
}