Example usage for com.rabbitmq.client ConnectionFactory setNetworkRecoveryInterval

List of usage examples for com.rabbitmq.client ConnectionFactory setNetworkRecoveryInterval

Introduction

In this page you can find the example usage for com.rabbitmq.client ConnectionFactory setNetworkRecoveryInterval.

Prototype

public void setNetworkRecoveryInterval(long networkRecoveryInterval) 

Source Link

Document

Sets connection recovery interval.

Usage

From source file:com.novemberain.langohr.Connection.java

License:Open Source License

public Connection(ConnectionFactory cf, IPersistentMap options) {
    this.cf = cf;
    this.options = options;

    Long l = (Long) options.valAt(NETWORK_RECOVERY_DELAY_KEYWORD, DEFAULT_NETWORK_RECOVERY_DELAY);
    cf.setNetworkRecoveryInterval(l.intValue());

    this.automaticallyRecover = Util.isTruthy(options.valAt(AUTOMATICALLY_RECOVER_KEYWORD, true));
    this.automaticallyRecoverTopology = Util
            .isTruthy(options.valAt(AUTOMATICALLY_RECOVER_TOPOLOGY_KEYWORD, true));

    cf.setAutomaticRecoveryEnabled(this.automaticallyRecover);
    cf.setTopologyRecoveryEnabled(this.automaticallyRecoverTopology);
}

From source file:com.nxttxn.vramel.components.rabbitMQ.RabbitMQEndpoint.java

License:Apache License

private ConnectionFactory getOrCreateConnectionFactory() {
    if (connectionFactory == null) {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername(getUsername());
        factory.setPassword(getPassword());
        factory.setVirtualHost(getVhost());
        factory.setHost(getHostname());/*w w  w  . j  a  v a 2s. c  om*/
        factory.setPort(getPortNumber());
        if (getClientProperties() != null) {
            factory.setClientProperties(getClientProperties());
        }
        factory.setConnectionTimeout(getConnectionTimeout());
        factory.setRequestedChannelMax(getRequestedChannelMax());
        factory.setRequestedFrameMax(getRequestedFrameMax());
        factory.setRequestedHeartbeat(getRequestedHeartbeat());
        if (getSslProtocol() != null) {
            try {
                if (getSslProtocol().equals("true")) {
                    factory.useSslProtocol();
                } else if (getTrustManager() == null) {
                    factory.useSslProtocol(getSslProtocol());
                } else {
                    factory.useSslProtocol(getSslProtocol(), getTrustManager());
                }
            } catch (NoSuchAlgorithmException | KeyManagementException e) {
                throw new IllegalArgumentException("Invalid sslProtocol " + sslProtocol, e);
            }
        }
        if (getAutomaticRecoveryEnabled() != null) {
            factory.setAutomaticRecoveryEnabled(getAutomaticRecoveryEnabled());
        }
        if (getNetworkRecoveryInterval() != null) {
            factory.setNetworkRecoveryInterval(getNetworkRecoveryInterval());
        }
        if (getTopologyRecoveryEnabled() != null) {
            factory.setTopologyRecoveryEnabled(getTopologyRecoveryEnabled());
        }
        connectionFactory = factory;
    }
    return connectionFactory;
}

From source file:com.paxxis.cornerstone.messaging.service.amqp.AMQPServiceBusConnector.java

License:Apache License

protected void initConnection() {
    try {//from www. ja  v a  2 s.c  o m
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(host);
        factory.setPort(port);
        factory.setAutomaticRecoveryEnabled(autoRecover);
        factory.setConnectionTimeout(timeout);
        factory.setNetworkRecoveryInterval(recoveryInterval);
        factory.setRequestedHeartbeat(heartbeat);
        factory.setTopologyRecoveryEnabled(autoTopologyRecover);
        factory.setExceptionHandler(exceptionHandler);

        connection = factory.newConnection();
        session = (AMQPSession) createSession();
    } catch (IOException e) {
        logger.error(e);
        throw new RuntimeException(e);
    }
}

From source file:com.zero_x_baadf00d.play.module.rabbitmq.RabbitMQModuleImpl.java

License:Open Source License

/**
 * Build an instance./*from w w w .  j  a va 2  s.  c om*/
 *
 * @param lifecycle     The current application lifecyle
 * @param configuration The current application configuration
 * @since 16.05.19
 */
@Inject
public RabbitMQModuleImpl(final ApplicationLifecycle lifecycle, final Config configuration) {
    this.configuration = configuration;
    try {
        final String uri = configuration.getString(RabbitMQModuleImpl.RABBITMQ_CONN_URI);
        if (uri == null || uri.isEmpty()) {
            throw new RuntimeException("URI is empty");
        }
        final ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(uri);
        connectionFactory
                .setRequestedHeartbeat(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_CONN_HEARTBEAT));
        connectionFactory
                .setNetworkRecoveryInterval(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_CONN_RECOVERY));
        connectionFactory.setConnectionTimeout(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_CONN_TIMEOUT));
        connectionFactory.setAutomaticRecoveryEnabled(
                configuration.getBoolean(RabbitMQModuleImpl.RABBITMQ_AUTO_RECOVERY));
        if (uri.toLowerCase(Locale.ENGLISH).startsWith("amqps://")) {
            connectionFactory.useSslProtocol();
        }

        final ExecutorService es = Executors
                .newFixedThreadPool(configuration.getInt(RabbitMQModuleImpl.RABBITMQ_EXECUTOR));
        this.rabbitConnection = connectionFactory.newConnection(es);
        RabbitMQModuleImpl.LOGGER.info("RabbitMQ connected at {}",
                String.format("amqp%s://%s:%d/%s", connectionFactory.isSSL() ? "s" : "",
                        connectionFactory.getHost(), connectionFactory.getPort(),
                        connectionFactory.getVirtualHost()));
    } catch (Exception ex) {
        this.rabbitConnection = null;
        if (!this.configuration.getBoolean(RabbitMQModuleImpl.RABBITMQ_BYPASS_ERROR)) {
            RabbitMQModuleImpl.LOGGER.error("Can't initialize RabbitMQ module", ex);
            throw new RuntimeException(ex);
        } else {
            RabbitMQModuleImpl.LOGGER.warn("Can't initialize RabbitMQ module: {}", ex.getMessage());
        }
    }

    lifecycle.addStopHook(() -> {
        RabbitMQModuleImpl.LOGGER.info("Shutting down RabbitMQ");
        if (this.rabbitConnection != null) {
            this.rabbitConnection.close();
        }
        return CompletableFuture.completedFuture(null);
    });
}

From source file:io.bootique.rabbitmq.client.connection.ConnectionConfig.java

License:Apache License

public Connection createConnection(String connectionName) {
    com.rabbitmq.client.ConnectionFactory factory = createConnectionFactory();

    factory.setRequestedChannelMax(requestedChannelMax);
    factory.setRequestedFrameMax(requestedFrameMax);
    factory.setRequestedHeartbeat(requestedHeartbeat);
    factory.setConnectionTimeout(connectionTimeout);
    factory.setHandshakeTimeout(handshakeTimeout);
    factory.setShutdownTimeout(shutdownTimeout);
    factory.setAutomaticRecoveryEnabled(automaticRecoveryEnabled);
    factory.setTopologyRecoveryEnabled(topologyRecovery);
    factory.setNetworkRecoveryInterval(networkRecoveryInterval);

    LOGGER.info("Creating RabbitMQ connection.");
    try {//  www .  ja  v a 2 s. com
        return factory.newConnection();
    } catch (IOException | TimeoutException e) {
        throw new RuntimeException(String.format("Can't create connection \"%s\".", connectionName), e);
    }
}

From source file:net.roboconf.messaging.rabbitmq.internal.utils.RabbitMqUtils.java

License:Apache License

/**
 * Configures the connection factory with the right settings.
 * @param factory the connection factory
 * @param configuration the messaging configuration
 * @throws IOException if something went wrong
 * @see RabbitMqConstants/*from ww  w .j  av a  2s.  c  om*/
 */
public static void configureFactory(ConnectionFactory factory, Map<String, String> configuration)
        throws IOException {

    final Logger logger = Logger.getLogger(RabbitMqUtils.class.getName());
    logger.fine("Configuring a connection factory for RabbitMQ.");

    String messageServerIp = configuration.get(RABBITMQ_SERVER_IP);
    if (messageServerIp != null) {
        Map.Entry<String, Integer> entry = Utils.findUrlAndPort(messageServerIp);
        factory.setHost(entry.getKey());
        if (entry.getValue() > 0)
            factory.setPort(entry.getValue());
    }

    factory.setUsername(configuration.get(RABBITMQ_SERVER_USERNAME));
    factory.setPassword(configuration.get(RABBITMQ_SERVER_PASSWORD));

    // Timeout for connection establishment: 5s
    factory.setConnectionTimeout(5000);

    // Configure automatic reconnection
    factory.setAutomaticRecoveryEnabled(true);

    // Recovery interval: 10s
    factory.setNetworkRecoveryInterval(10000);

    // Exchanges and so on should be redeclared if necessary
    factory.setTopologyRecoveryEnabled(true);

    // SSL
    if (Boolean.parseBoolean(configuration.get(RABBITMQ_USE_SSL))) {
        logger.fine("Connection factory for RabbitMQ: SSL is used.");

        InputStream clientIS = null;
        InputStream storeIS = null;
        try {
            clientIS = new FileInputStream(configuration.get(RABBITMQ_SSL_KEY_STORE_PATH));
            storeIS = new FileInputStream(configuration.get(RABBITMQ_SSL_TRUST_STORE_PATH));

            char[] keyStorePassphrase = configuration.get(RABBITMQ_SSL_KEY_STORE_PASSPHRASE).toCharArray();
            KeyStore ks = KeyStore.getInstance(
                    getValue(configuration, RABBITMQ_SSL_KEY_STORE_TYPE, DEFAULT_SSL_KEY_STORE_TYPE));
            ks.load(clientIS, keyStorePassphrase);

            String value = getValue(configuration, RABBITMQ_SSL_KEY_MNGR_FACTORY, DEFAULT_SSL_MNGR_FACTORY);
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(value);
            kmf.init(ks, keyStorePassphrase);

            char[] trustStorePassphrase = configuration.get(RABBITMQ_SSL_TRUST_STORE_PASSPHRASE).toCharArray();
            KeyStore tks = KeyStore.getInstance(
                    getValue(configuration, RABBITMQ_SSL_TRUST_STORE_TYPE, DEFAULT_SSL_TRUST_STORE_TYPE));
            tks.load(storeIS, trustStorePassphrase);

            value = getValue(configuration, RABBITMQ_SSL_TRUST_MNGR_FACTORY, DEFAULT_SSL_MNGR_FACTORY);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(value);
            tmf.init(tks);

            SSLContext c = SSLContext
                    .getInstance(getValue(configuration, RABBITMQ_SSL_PROTOCOL, DEFAULT_SSL_PROTOCOL));
            c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
            factory.useSslProtocol(c);

        } catch (GeneralSecurityException e) {
            throw new IOException("SSL configuration for the RabbitMQ factory failed.", e);

        } finally {
            Utils.closeQuietly(storeIS);
            Utils.closeQuietly(clientIS);
        }
    }
}

From source file:org.apache.flink.streaming.connectors.rabbitmq.common.RMQConnectionConfig.java

License:Apache License

/**
 *
 * @return Connection Factory for RMQ//from  ww w.  j  a  v  a2  s.co  m
 * @throws URISyntaxException, NoSuchAlgorithmException, KeyManagementException if Malformed URI has been passed
 */
public ConnectionFactory getConnectionFactory()
        throws URISyntaxException, NoSuchAlgorithmException, KeyManagementException {
    ConnectionFactory factory = new ConnectionFactory();
    if (this.uri != null && !this.uri.isEmpty()) {
        try {
            factory.setUri(this.uri);
        } catch (URISyntaxException | NoSuchAlgorithmException | KeyManagementException e) {
            LOG.error("Failed to parse uri", e);
            throw e;
        }
    } else {
        factory.setHost(this.host);
        factory.setPort(this.port);
        factory.setVirtualHost(this.virtualHost);
        factory.setUsername(this.username);
        factory.setPassword(this.password);
    }

    if (this.automaticRecovery != null) {
        factory.setAutomaticRecoveryEnabled(this.automaticRecovery);
    }
    if (this.connectionTimeout != null) {
        factory.setConnectionTimeout(this.connectionTimeout);
    }
    if (this.networkRecoveryInterval != null) {
        factory.setNetworkRecoveryInterval(this.networkRecoveryInterval);
    }
    if (this.requestedHeartbeat != null) {
        factory.setRequestedHeartbeat(this.requestedHeartbeat);
    }
    if (this.topologyRecovery != null) {
        factory.setTopologyRecoveryEnabled(this.topologyRecovery);
    }
    if (this.requestedChannelMax != null) {
        factory.setRequestedChannelMax(this.requestedChannelMax);
    }
    if (this.requestedFrameMax != null) {
        factory.setRequestedFrameMax(this.requestedFrameMax);
    }

    return factory;
}

From source file:org.belio.mq.RabbitConsumer.java

@Override
public void open() throws IOException {

    try {//from  ww  w .j ava2s  . co  m
        com.rabbitmq.client.ConnectionFactory factory = new com.rabbitmq.client.ConnectionFactory();
        factory.setHost(mqproperties.getProperty("host"));
        factory.setVirtualHost(mqproperties.getProperty("vhost"));
        factory.setUsername(mqproperties.getProperty("username"));
        factory.setPassword(mqproperties.getProperty("password"));
        factory.setPort(Integer.parseInt(mqproperties.getProperty("port")));
        factory.setAutomaticRecoveryEnabled(true);
        factory.setNetworkRecoveryInterval(1);
        // Create a new connection to MQ
        connection = factory.newConnection();
        // Create a new channel and declare it's type and exhange as well
        //Create a new rabbit publisher           
        executor = Executors.newScheduledThreadPool(
                Integer.parseInt(threadproperties.getProperty(queueType.name().toLowerCase()).split(",")[0]));

    } catch (IOException ex) {
        Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ShutdownSignalException ex) {
        Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ConsumerCancelledException ex) {
        Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:org.onosproject.rabbitmq.impl.MQSender.java

License:Apache License

@Override
public void start() {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setAutomaticRecoveryEnabled(true);
    factory.setNetworkRecoveryInterval(RECOVERY_INTERVAL);
    try {/*w w w .  ja  v a2 s  .  co m*/
        factory.setUri(url);
        if (executorService != null) {
            conn = factory.newConnection(executorService);
        } else {
            conn = factory.newConnection();
        }
        channel = conn.createChannel();
        channel.exchangeDeclare(exchangeName, TOPIC, true);
        /*
         * Setting the following parameters to queue
         * durable    - true
         * exclusive  - false
         * autoDelete - false
         * arguments  - null
         */
        channel.queueDeclare(this.queueName, true, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);
    } catch (Exception e) {
        log.error(E_CREATE_CHAN, e);
    }
}

From source file:org.wso2.carbon.event.adapter.rabbitmq.internal.util.RabbitMQOutputEventAdapterPublisher.java

License:Open Source License

/**
 * <pre>//from  w  w  w  .j a v a 2 s. co m
 * Create a rabbitmq ConnectionFactory instance
 * </pre>
 * @param hostName
 * @param port
 * @param userName
 * @param password
 * @param virtualHost
 * @return
 */
private synchronized static ConnectionFactory getConnectionFactory(String hostName, int port, String userName,
        String password, String virtualHost) {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(hostName);
    factory.setPort(port);
    factory.setUsername(userName);
    factory.setPassword(password);
    factory.setVirtualHost(virtualHost);

    /**
     * Add connection recovery logic
     * @author Sang-Cheon Park
     * @date 2015.07.16
     */
    /**
     * connection that will recover automatically
     */
    factory.setAutomaticRecoveryEnabled(true);
    /**
     * attempt recovery every 5 seconds
     */
    factory.setNetworkRecoveryInterval(5 * 1000);
    /**
     * wait maximum 10 seconds to connect(if connection failed, will be retry to connect after 5 seconds)
     */
    factory.setConnectionTimeout(10 * 1000);

    return factory;
}