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:biospectra.classify.server.RabbitMQInputClient.java

License:Apache License

public synchronized void connect() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    String hostname = this.conf.getRabbitMQHostnames().get(this.hostId);
    factory.setHost(hostname);/*from   w w  w.j a v  a  2s .  c o m*/
    factory.setPort(this.conf.getRabbitMQPort());
    factory.setUsername(this.conf.getRabbitMQUserId());
    factory.setPassword(this.conf.getRabbitMQUserPwd());

    factory.setRequestedHeartbeat(60);

    factory.setAutomaticRecoveryEnabled(true);

    this.connection = factory.newConnection();
    this.shutdownListener = new ShutdownListener() {

        @Override
        public void shutdownCompleted(ShutdownSignalException sse) {
            LOG.error("connection shutdown", sse);
        }
    };

    this.connection.addShutdownListener(this.shutdownListener);

    this.requestChannel = this.connection.createChannel();
    this.responseChannel = this.connection.createChannel();

    LOG.info("reader connected - " + hostname + ":" + this.conf.getRabbitMQPort());

    this.responseChannel.basicQos(10);
    this.queueName = this.responseChannel.queueDeclare().getQueue();

    this.consumer = new DefaultConsumer(this.responseChannel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");

            this.getChannel().basicAck(envelope.getDeliveryTag(), false);

            LOG.info("> " + message);

            ClassificationResponseMessage res = ClassificationResponseMessage.createInstance(message);
            ClassificationRequest ereq = null;
            synchronized (requestMap) {
                ereq = requestMap.get(res.getReqId());
                if (ereq != null) {
                    requestMap.remove(res.getReqId());
                }
            }

            if (ereq == null) {
                LOG.error("cannot find matching request");
            } else {
                ClassificationResponse eres = new ClassificationResponse(ereq, res);

                boolean responded = false;
                synchronized (ereq) {
                    ClassificationRequest.RequestStatus status = ereq.getStatus();
                    if (status.equals(ClassificationRequest.RequestStatus.STATUS_UNKNOWN)) {
                        ereq.setStatus(ClassificationRequest.RequestStatus.STATUS_RESPONDED);
                        responded = true;
                    }

                    requestQueue.remove(ereq);
                }

                if (responded) {
                    LOG.info("res : " + ereq.getReqId());
                    if (handler != null) {
                        handler.onSuccess(eres.getReqId(), eres.getHeader(), eres.getSequence(),
                                eres.getResult(), eres.getType(), eres.getTaxonRank(), eres.getTaxonName());
                    }

                    synchronized (requestQueue) {
                        requestQueue.notifyAll();
                    }
                }
            }
        }
    };

    this.workerThread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                responseChannel.basicConsume(queueName, consumer);
                LOG.info("Waiting for messages");
            } catch (IOException ex) {
                LOG.error("Exception occurred while consuming a message", ex);
            }
        }
    });
    this.workerThread.start();
    this.reachable = true;

    this.timeoutThread = new Thread(new Runnable() {

        @Override
        public void run() {
            while (true) {
                boolean cont = false;
                if (requestQueue.size() > 0) {
                    ClassificationRequest ereq = requestQueue.peek();
                    Date cur = new Date();
                    if (ereq != null && cur.getTime() - ereq.getSentTime() >= QUERY_TIMEOUT) {
                        LOG.info("found timeout request");
                        //timeout
                        boolean timeout = false;
                        synchronized (ereq) {
                            ClassificationRequest.RequestStatus status = ereq.getStatus();
                            if (status.equals(ClassificationRequest.RequestStatus.STATUS_UNKNOWN)) {
                                ereq.setStatus(ClassificationRequest.RequestStatus.STATUS_TIMEOUT);
                                timeout = true;
                            }

                            requestQueue.remove(ereq);
                        }

                        synchronized (requestMap) {
                            requestMap.remove(ereq.getReqId());
                        }

                        if (timeout) {
                            LOG.info("timeout : " + ereq.getReqId());
                            handler.onTimeout(ereq.getReqId(), ereq.getHeader(), ereq.getSequence());

                            synchronized (requestQueue) {
                                requestQueue.notifyAll();
                            }
                        }
                        cont = true;
                    }
                }

                if (!cont) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                        break;
                    }
                }
            }
        }
    });
    this.timeoutThread.start();
}

From source file:biospectra.classify.server.RabbitMQInputServer.java

License:Apache License

public synchronized void connect() throws IOException, TimeoutException {
    LOG.info("Connecting to - " + this.conf.getRabbitMQHostname() + ":" + this.conf.getRabbitMQPort());

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(this.conf.getRabbitMQHostname());
    factory.setPort(this.conf.getRabbitMQPort());
    factory.setUsername(this.conf.getRabbitMQUserId());
    factory.setPassword(this.conf.getRabbitMQUserPwd());

    factory.setRequestedHeartbeat(60);/*www  .  j  a  va2  s. com*/

    factory.setAutomaticRecoveryEnabled(true);

    this.connection = factory.newConnection();
    this.connection.addShutdownListener(new ShutdownListener() {

        @Override
        public void shutdownCompleted(ShutdownSignalException sse) {
            LOG.error("connection shutdown", sse);
        }
    });

    this.requestChannel = this.connection.createChannel();
    this.responseChannel = this.connection.createChannel();

    LOG.info("connected.");

    this.requestChannel.basicQos(1);
    this.requestChannel.queueDeclare("request", false, false, true, null);

    this.responseChannel.addReturnListener(new ReturnListener() {

        @Override
        public void handleReturn(int replyCode, String replyText, String exchange, String routingKey,
                AMQP.BasicProperties properties, byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            LOG.info("message not delivered to " + routingKey);
            LOG.info(message);
        }
    });

    this.consumer = new DefaultConsumer(this.requestChannel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");

            this.getChannel().basicAck(envelope.getDeliveryTag(), false);

            if (handler != null) {
                ClassificationRequestMessage req = ClassificationRequestMessage.createInstance(message);
                handler.handleMessage(req, properties.getReplyTo());
            }
        }
    };

    this.workerThread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                requestChannel.basicConsume("request", consumer);
                LOG.info("Waiting for messages");
            } catch (IOException ex) {
                LOG.error("Exception occurred while consuming a message", ex);
            }
        }
    });
    this.workerThread.start();
}

From source file:ch.icclab.cyclops.consume.RabbitMQListener.java

License:Open Source License

/**
 * Will return channel for RabbitMQ connection
 * @return channel reference or null//from  w ww.j  a va 2  s  .  c o  m
 */
private Channel getChannel() {
    // connect to the RabbitMQ based on settings from Load
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(credentials.getConsumerUsername());
    factory.setPassword(credentials.getConsumerPassword());
    factory.setHost(credentials.getConsumerHost());
    factory.setPort(credentials.getConsumerPort());
    factory.setVirtualHost(credentials.getConsumerVirtualHost());
    factory.setAutomaticRecoveryEnabled(true);

    Channel chan;

    try {
        // create new connection
        connection = factory.newConnection();

        // create/connect to the channel
        chan = connection.createChannel();

        logger.trace(String.format("RabbitMQ Consumer connected to %s:%d", credentials.getConsumerHost(),
                credentials.getConsumerPort()));

    } catch (Exception e) {
        logger.error(String.format("RabbitMQ Consumer couldn't be created: %s", e.getMessage()));
        connection = null;
        chan = null;
    }

    // return channel reference, or null
    return chan;
}

From source file:ch.icclab.cyclops.publish.RabbitMQPublisher.java

License:Open Source License

/**
 * Initialise connection to RabbitMQ// www .j  ava 2s.c om
 * @return status
 */
private Boolean initialiseConnection() {
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername(credentials.getPublisherUsername());
        factory.setPassword(credentials.getPublisherPassword());
        factory.setHost(credentials.getPublisherHost());
        factory.setPort(credentials.getPublisherPort());
        factory.setVirtualHost(credentials.getPublisherVirtualHost());
        factory.setAutomaticRecoveryEnabled(true);

        connection = factory.newConnection();
        channel = connection.createChannel();

        // declare exchange to be used (we want it to be durable and based on routing key)
        channel.exchangeDeclare(credentials.getPublisherDispatchExchange(), "direct", true);
        channel.exchangeDeclare(credentials.getPublisherBroadcastExchange(), "fanout", true);

        logger.trace(String.format("RabbitMQ Publisher connected to %s:%d", credentials.getPublisherHost(),
                credentials.getPublisherPort()));
        logger.trace(String.format(
                "RabbitMQ Publisher will dispatch to \"%s\" and broadcast to \"%s\" exchanges",
                credentials.getPublisherDispatchExchange(), credentials.getPublisherBroadcastExchange()));

        return true;
    } catch (Exception e) {
        logger.error(String.format("RabbitMQ Publisher couldn't be created: %s", e.getMessage()));
        return false;
    }
}

From source file:com.cisco.oss.foundation.message.ChannelWrapper.java

License:Apache License

static void connect() {
    try {//from w ww .  j  a  va2  s  .com

        Configuration configuration = ConfigurationFactory.getConfiguration();

        final Map<String, Map<String, String>> serverConnections = ConfigUtil
                .parseComplexArrayStructure("service.rabbitmq.connections");
        final ArrayList<String> serverConnectionKeys = Lists.newArrayList(serverConnections.keySet());
        Collections.sort(serverConnectionKeys);

        int maxRetryAttempts = configuration.getInt("service.rabbitmq.maxRetryAttempts", 1000);

        Config config = new Config()
                .withRecoveryPolicy(new RecoveryPolicy().withBackoff(Duration.seconds(1), Duration.seconds(30))
                        .withMaxAttempts(maxRetryAttempts))
                .withConnectionRecoveryPolicy(
                        new RecoveryPolicy().withBackoff(Duration.seconds(1), Duration.seconds(30))
                                .withMaxAttempts(maxRetryAttempts))
                .withConsumerRecovery(true).withExchangeRecovery(true).withQueueRecovery(true)
                .withConnectionListeners(new ConnectionListener() {
                    @Override
                    public void onCreate(Connection connection) {
                        LOGGER.trace("connection create: {}", connection);
                    }

                    @Override
                    public void onCreateFailure(Throwable failure) {
                        LOGGER.error("connection create failed: {}", failure.toString(), failure);
                        IS_CONNECCTION_OR_CHANNEL_UP.set(false);
                    }

                    @Override
                    public void onRecoveryStarted(Connection connection) {
                        LOGGER.trace("connection recovery started: {}", connection);
                        IS_CONNECCTION_OR_CHANNEL_UP.set(false);

                    }

                    @Override
                    public void onRecovery(Connection connection) {
                        LOGGER.trace("connection recovered: {}", connection);
                    }

                    @Override
                    public void onRecoveryCompleted(Connection connection) {
                        LOGGER.trace("connection recovery completed: {}", connection);
                        IS_CONNECCTION_OR_CHANNEL_UP.set(true);
                    }

                    @Override
                    public void onRecoveryFailure(Connection connection, Throwable failure) {
                        LOGGER.error("connection recovery failed: {}", failure.toString(), failure);
                        IS_CONNECCTION_OR_CHANNEL_UP.set(false);
                    }
                }).withChannelListeners(new ChannelListener() {
                    @Override
                    public void onCreate(Channel channel) {
                        LOGGER.trace("channel create: {}", channel);
                    }

                    @Override
                    public void onCreateFailure(Throwable failure) {
                        LOGGER.error("channel create failed: {}", failure.toString(), failure);
                        IS_CONNECCTION_OR_CHANNEL_UP.set(false);
                    }

                    @Override
                    public void onRecoveryStarted(Channel channel) {
                        LOGGER.trace("channel recovery started: {}", channel);
                        IS_CONNECCTION_OR_CHANNEL_UP.set(false);
                    }

                    @Override
                    public void onRecovery(Channel channel) {
                        LOGGER.trace("channel recovered: {}", channel);
                    }

                    @Override
                    public void onRecoveryCompleted(Channel channel) {
                        LOGGER.trace("channel recovery completed: {}", channel);
                        IS_CONNECCTION_OR_CHANNEL_UP.set(true);
                    }

                    @Override
                    public void onRecoveryFailure(Channel channel, Throwable failure) {
                        LOGGER.error("channel recovery failed: {}", failure.toString(), failure);
                        IS_CONNECCTION_OR_CHANNEL_UP.set(false);
                    }
                }).withConsumerListeners(new ConsumerListener() {
                    @Override
                    public void onRecoveryStarted(Consumer consumer, Channel channel) {
                        LOGGER.trace("consumer create. consumer: {}, channel: {}", consumer, channel);
                        IS_CONSUMER_UP.set(false);
                    }

                    @Override
                    public void onRecoveryCompleted(Consumer consumer, Channel channel) {
                        LOGGER.trace("consumer recovery completed: {}, channel: {}", consumer, channel);
                        IS_CONSUMER_UP.set(true);
                    }

                    @Override
                    public void onRecoveryFailure(Consumer consumer, Channel channel, Throwable failure) {
                        LOGGER.error("consumer recovery failed. consumer: {}, channel: {}, error: {}", consumer,
                                channel, failure.toString(), failure);
                        IS_CONSUMER_UP.set(false);
                    }
                });

        config.getRecoverableExceptions().add(UnknownHostException.class);
        config.getRecoverableExceptions().add(NoRouteToHostException.class);

        List<Address> addresses = new ArrayList<>(5);

        for (String serverConnectionKey : serverConnectionKeys) {

            Map<String, String> serverConnection = serverConnections.get(serverConnectionKey);

            String host = serverConnection.get("host");
            int port = Integer.parseInt(serverConnection.get("port"));
            addresses.add(new Address(host, port));
        }
        Address[] addrs = new Address[0];

        ConnectionOptions options = new ConnectionOptions().withAddresses(addresses.toArray(addrs));

        final ConnectionFactory connectionFactory = options.getConnectionFactory();
        connectionFactory.setAutomaticRecoveryEnabled(false);
        connectionFactory.setTopologyRecoveryEnabled(false);

        final boolean metricsAndMonitoringIsEnabled = configuration
                .getBoolean("service.rabbitmq.metricsAndMonitoringJmx.isEnabled", false);

        if (metricsAndMonitoringIsEnabled) {
            MetricRegistry registry = new MetricRegistry();
            StandardMetricsCollector metrics = new StandardMetricsCollector(registry);
            connectionFactory.setMetricsCollector(metrics);

            JmxReporter reporter = JmxReporter.forRegistry(registry).inDomain("com.rabbitmq.client.jmx")
                    .build();
            reporter.start();
        }

        final boolean useNio = configuration.getBoolean("service.rabbitmq.useNio", false);

        if (useNio) {
            NioParams nioParams = new NioParams();

            final Integer nbIoThreads = configuration.getInteger("service.rabbitmq.nio.nbIoThreads", null);
            final Integer readByteBufferSize = configuration
                    .getInteger("service.rabbitmq.nio.readByteBufferSize", null);
            final Integer writeByteBufferSize = configuration
                    .getInteger("service.rabbitmq.nio.writeByteBufferSize", null);
            final Integer writeEnqueuingTimeoutInMs = configuration
                    .getInteger("service.rabbitmq.nio.writeEnqueuingTimeoutInMs", null);
            final Integer writeQueueCapacity = configuration
                    .getInteger("service.rabbitmq.nio.writeQueueCapacity", null);

            if (nbIoThreads != null) {
                nioParams.setNbIoThreads(nbIoThreads);
            }
            if (readByteBufferSize != null) {
                nioParams.setReadByteBufferSize(readByteBufferSize);
            }
            if (writeByteBufferSize != null) {
                nioParams.setWriteByteBufferSize(writeByteBufferSize);
            }
            if (writeEnqueuingTimeoutInMs != null) {
                nioParams.setWriteEnqueuingTimeoutInMs(writeEnqueuingTimeoutInMs);
            }
            if (writeQueueCapacity != null) {
                nioParams.setWriteQueueCapacity(writeQueueCapacity);
            }

            //                nioParams.setNioExecutor()
            //                nioParams.setThreadFactory()

            options.withNio().withNioParams(nioParams);
        }

        Configuration subsetBase = configuration.subset("service.rabbitmq");
        Configuration subsetSecurity = subsetBase.subset("security");

        int requestHeartbeat = subsetBase.getInt("requestHeartbeat", 10);
        options.withRequestedHeartbeat(Duration.seconds(requestHeartbeat));

        String userName = subsetSecurity.getString("userName");
        String password = subsetSecurity.getString("password");
        boolean isEnabled = subsetSecurity.getBoolean("isEnabled");

        if (isEnabled) {
            options.withUsername(userName).withPassword(password);

        }

        connection = Connections.create(options, config);

        connection.addBlockedListener(new BlockedListener() {
            public void handleBlocked(String reason) throws IOException {
                LOGGER.error("RabbitMQ connection is now blocked. Port: {}, Reason: {}", connection.getPort(),
                        reason);
                IS_BLOCKED.set(true);
            }

            public void handleUnblocked() throws IOException {
                LOGGER.info("RabbitMQ connection is now un-blocked. Port: {}", connection.getPort());
                IS_BLOCKED.set(false);
            }
        });

        connection.addShutdownListener(new ShutdownListener() {
            @Override
            public void shutdownCompleted(ShutdownSignalException cause) {
                LOGGER.error("Connection shutdown detected. Reason: {}", cause.toString(), cause);
                IS_CONNECTED.set(false);
            }
        });

        IS_CONNECTED.set(true);
        IS_CONNECCTION_OR_CHANNEL_UP.set(true);
        IS_CONSUMER_UP.set(true);
        INIT_LATCH.countDown();

    } catch (Exception e) {
        LOGGER.error("can't create RabbitMQ Connection: {}", e, e);
        //            triggerReconnectThread();
        throw new QueueException(e);
    }
}

From source file:com.codio.collab.core.queue.QueueFactory.java

License:Apache License

private void openConnection() {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setVirtualHost(getConnectionConfig().getVhost());
    factory.setUsername(getConnectionConfig().getUser());
    factory.setPassword(getConnectionConfig().getPassword());
    factory.setPort(getConnectionConfig().getPort());
    factory.setHost(getConnectionConfig().getHost());
    factory.setAutomaticRecoveryEnabled(true);
    try {//from   w  ww  .  j  ava  2s  .  c  om
        connection = factory.newConnection();
    } catch (IOException e) {
        LOG.error("Can not open rmq connection {}", e.getMessage());
    }
}

From source file:com.flipkart.bifrost.framework.Connection.java

License:Apache License

/**
 * Start the connection. This will try to connect to the cluster hosts provided in the contructor.
 * Will throw an error in case of failure.
 * @throws BifrostException in case of connection failure.
 */// w w w  .j a  v  a  2s.c  om
public void start() throws BifrostException {
    ConnectionFactory connectionFactory = new ConnectionFactory();
    Address brokers[] = new Address[hosts.size()];
    int i = 0;
    for (String member : hosts) {
        brokers[i++] = new Address(member);
    }
    connectionFactory.setUsername(username);
    connectionFactory.setPassword(password);
    connectionFactory.setAutomaticRecoveryEnabled(true);
    connectionFactory.setTopologyRecoveryEnabled(true);
    try {
        connection = connectionFactory.newConnection(brokers);
    } catch (IOException e) {
        throw new BifrostException(BifrostException.ErrorCode.IO_ERROR, "Could not connect", e);
    }
}

From source file:com.hp.ov.sdk.messaging.core.RabbitMqClientConnectionFactory.java

License:Apache License

public static ConnectionFactory getConnectionFactory(final SSLContext sslContext, final RestParams params) {

    final ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(params.getHostname());
    factory.setPort(params.getAmqpPort());

    // Set Auth mechanism to "EXTERNAL" so that commonName of the client
    // certificate is mapped to AMQP user name. Hence, No need to set
    // userId/Password here.
    factory.setSaslConfig(DefaultSaslConfig.EXTERNAL);
    factory.useSslProtocol(sslContext);/*from  w  w  w.  j a  va  2s  . c  o  m*/
    factory.setAutomaticRecoveryEnabled(true);

    return factory;
}

From source file:com.jarova.mqtt.RabbitMQ.java

public void fixConnection() {
    try {/*from www  .  java 2s.c  o  m*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername(USER_NAME);
        factory.setPassword(PASSWORD);
        factory.setHost(HOST_NAME);

        //adicionado para que a conexao seja recuperada em caso de falha de rede;
        factory.setAutomaticRecoveryEnabled(true);

        Connection connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(QUEUE, true, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
    } catch (IOException ex) {
        Logger.getLogger(RabbitMQ.class.getName()).log(Level.SEVERE, null, ex);
    } catch (TimeoutException ex) {
        Logger.getLogger(RabbitMQ.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.navercorp.pinpoint.plugin.jdk7.rabbitmq.RabbitMQClient_3_3_0_to_4_0_0_IT.java

License:Apache License

@Test
public void testPush() throws Exception {
    ConnectionFactory connectionFactory = getConnectionFactory();
    connectionFactory.setAutomaticRecoveryEnabled(false);

    testRunner.runPushTest();/*from w w w . j a v  a2 s .co m*/
}