Example usage for com.rabbitmq.client ConnectionFactory setAutomaticRecoveryEnabled

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

Introduction

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

Prototype

public void setAutomaticRecoveryEnabled(boolean automaticRecovery) 

Source Link

Document

Enables or disables <a href="https://www.rabbitmq.com/api-guide.html#recovery">automatic connection recovery</a>.

Usage

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 .  ja v  a  2s .c o m*/
 */
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.airavata.messaging.core.impl.RabbitMQProcessLaunchConsumer.java

License:Apache License

private void createConnection() throws AiravataException {
    try {/* w  ww  .  j ava2  s  .c om*/
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(url);
        connectionFactory.setAutomaticRecoveryEnabled(true);
        connection = connectionFactory.newConnection();
        connection.addShutdownListener(new ShutdownListener() {
            public void shutdownCompleted(ShutdownSignalException cause) {
            }
        });
        log.info("connected to rabbitmq: " + connection + " for " + taskLaunchExchangeName);

        channel = connection.createChannel();
        channel.basicQos(prefetchCount);

        //            channel.exchangeDeclare(taskLaunchExchangeName, "fanout");

    } catch (Exception e) {
        String msg = "could not open channel for exchange " + taskLaunchExchangeName;
        log.error(msg);
        throw new AiravataException(msg, e);
    }
}

From source file:org.apache.airavata.messaging.core.impl.RabbitMQProducer.java

License:Apache License

private Connection createConnection() throws IOException {
    try {//from w  w w.ja va  2  s.co m
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(url);
        connectionFactory.setAutomaticRecoveryEnabled(true);
        Connection connection = connectionFactory.newConnection();
        connection.addShutdownListener(new ShutdownListener() {
            public void shutdownCompleted(ShutdownSignalException cause) {
            }
        });
        log.info("connected to rabbitmq: " + connection + " for " + exchangeName);
        return connection;
    } catch (Exception e) {
        log.info("connection failed to rabbitmq: " + connection + " for " + exchangeName);
        return null;
    }
}

From source file:org.apache.airavata.messaging.core.impl.RabbitMQPublisher.java

License:Apache License

private void connect() throws AiravataException {
    try {/*w  w w .ja v a 2s.c o  m*/
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(properties.getBrokerUrl());
        connectionFactory.setAutomaticRecoveryEnabled(properties.isAutoRecoveryEnable());
        connection = connectionFactory.newConnection();
        connection.addShutdownListener(new ShutdownListener() {
            public void shutdownCompleted(ShutdownSignalException cause) {
            }
        });
        log.info("connected to rabbitmq: " + connection + " for " + properties.getExchangeName());
        channel = connection.createChannel();
        if (properties.getPrefetchCount() > 0) {
            channel.basicQos(properties.getPrefetchCount());
        }

        if (properties.getExchangeName() != null) {
            channel.exchangeDeclare(properties.getExchangeName(), properties.getExchangeType(), true); //durable
        }
    } catch (Exception e) {
        String msg = "RabbitMQ connection issue for exchange : " + properties.getExchangeName();
        log.error(msg);
        throw new AiravataException(msg, e);
    }

}

From source file:org.apache.airavata.messaging.core.impl.RabbitMQStatusConsumer.java

License:Apache License

private void createConnection() throws AiravataException {
    try {/*from  w w  w  .ja  v a2 s  .  c  o m*/
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(url);
        connectionFactory.setAutomaticRecoveryEnabled(true);
        connection = connectionFactory.newConnection();
        connection.addShutdownListener(new ShutdownListener() {
            public void shutdownCompleted(ShutdownSignalException cause) {
            }
        });
        log.info("connected to rabbitmq: " + connection + " for " + exchangeName);

        channel = connection.createChannel();
        channel.basicQos(prefetchCount);
        channel.exchangeDeclare(exchangeName, EXCHANGE_TYPE, false);

    } catch (Exception e) {
        String msg = "could not open channel for exchange " + exchangeName;
        log.error(msg);
        throw new AiravataException(msg, e);
    }
}

From source file:org.apache.airavata.messaging.core.impl.RabbitMQSubscriber.java

License:Apache License

private void createConnection() throws AiravataException {
    try {/*from  w w  w  .  ja v  a  2 s  .c  o m*/
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri(properties.getBrokerUrl());
        connectionFactory.setAutomaticRecoveryEnabled(properties.isAutoRecoveryEnable());
        connection = connectionFactory.newConnection();
        addShutdownListener();
        log.info("connected to rabbitmq: " + connection + " for " + properties.getExchangeName());
        channel = connection.createChannel();
        channel.basicQos(properties.getPrefetchCount());
        channel.exchangeDeclare(properties.getExchangeName(), properties.getExchangeType(), true); // durable
    } catch (Exception e) {
        String msg = "could not open channel for exchange " + properties.getExchangeName();
        log.error(msg);
        throw new AiravataException(msg, e);
    }
}

From source file:org.apache.airavata.monitoring.consumer.StatusReceiver.java

License:Apache License

public void startThread() throws KeyManagementException, NoSuchAlgorithmException, URISyntaxException,
        IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setAutomaticRecoveryEnabled(true);
    factory.setUri(brokerURI);//www  . j  a  v a2  s .c  om
    connection = factory.newConnection();
    recieverThread = new Thread(this);
    recieverThread.start();
}

From source file:org.apache.axis2.transport.rabbitmq.ConnectionFactoryManager.java

License:Open Source License

/**
 * Get the connection factory that matches the given name, i.e. referring to
 * the same underlying connection factory. Used by the RabbitMQSender to determine if already
 * available resources should be used for outgoing messages. If no factory instance is
 * found then a new one will be created and added to the connection factory map
 *
 * @param props a Map of connection factory properties and name
 * @return the connection factory or null if no connection factory compatible
 *         with the given properties exists
 *//*from www.j  a v a2 s.c  om*/
public ConnectionFactory getAMQPConnectionFactory(Hashtable<String, String> props) {
    ConnectionFactory connectionFactory = null;
    String hostName = props.get(RabbitMQConstants.SERVER_HOST_NAME);
    String portValue = props.get(RabbitMQConstants.SERVER_PORT);
    String hostAndPort = hostName + ":" + portValue;
    connectionFactory = connectionFactories.get(hostAndPort);

    if (connectionFactory == null) {
        com.rabbitmq.client.ConnectionFactory factory = new com.rabbitmq.client.ConnectionFactory();
        if (hostName != null && !hostName.equals("")) {
            factory.setHost(hostName);
        } else {
            throw new AxisRabbitMQException("Host name is not correctly defined");
        }
        int port = Integer.parseInt(portValue);
        if (port > 0) {
            factory.setPort(port);
        }
        String userName = props.get(RabbitMQConstants.SERVER_USER_NAME);

        if (userName != null && !userName.equals("")) {
            factory.setUsername(userName);
        }

        String password = props.get(RabbitMQConstants.SERVER_PASSWORD);

        if (password != null && !password.equals("")) {
            factory.setPassword(password);
        }
        String virtualHost = props.get(RabbitMQConstants.SERVER_VIRTUAL_HOST);

        if (virtualHost != null && !virtualHost.equals("")) {
            factory.setVirtualHost(virtualHost);
        }
        factory.setAutomaticRecoveryEnabled(true);
        factory.setTopologyRecoveryEnabled(false);
        connectionFactory = new ConnectionFactory(hostAndPort, factory);
        connectionFactories.put(connectionFactory.getName(), connectionFactory);
    }

    return connectionFactory;
}

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 a  2  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   w w w. j a  v  a2s  .  c o 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);
    }

}