Example usage for com.rabbitmq.client Connection addBlockedListener

List of usage examples for com.rabbitmq.client Connection addBlockedListener

Introduction

In this page you can find the example usage for com.rabbitmq.client Connection addBlockedListener.

Prototype

void addBlockedListener(BlockedListener listener);

Source Link

Document

Add a BlockedListener .

Usage

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

License:Apache License

static void connect() {
    try {/*from   w w w  .ja  v a  2s .  c o  m*/

        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:org.springframework.amqp.rabbit.connection.ConnectionFactoryLifecycleTests.java

License:Apache License

@Test
public void testBlockedConnection() throws Exception {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);

    AtomicReference<ConnectionBlockedEvent> blockedConnectionEvent = new AtomicReference<>();
    AtomicReference<ConnectionUnblockedEvent> unblockedConnectionEvent = new AtomicReference<>();

    context.addApplicationListener((ApplicationListener<ConnectionBlockedEvent>) blockedConnectionEvent::set);

    context.addApplicationListener(//from   www .j  a va  2 s  .c o m
            (ApplicationListener<ConnectionUnblockedEvent>) unblockedConnectionEvent::set);

    CachingConnectionFactory cf = context.getBean(CachingConnectionFactory.class);

    CountDownLatch blockedConnectionLatch = new CountDownLatch(1);
    CountDownLatch unblockedConnectionLatch = new CountDownLatch(1);

    Connection connection = cf.createConnection();
    connection.addBlockedListener(new BlockedListener() {

        @Override
        public void handleBlocked(String reason) throws IOException {
            blockedConnectionLatch.countDown();
        }

        @Override
        public void handleUnblocked() throws IOException {
            unblockedConnectionLatch.countDown();
        }

    });

    AMQConnection amqConnection = TestUtils.getPropertyValue(connection, "target.delegate",
            AMQConnection.class);
    amqConnection
            .processControlCommand(new AMQCommand(new AMQImpl.Connection.Blocked("Test connection blocked")));

    assertTrue(blockedConnectionLatch.await(10, TimeUnit.SECONDS));

    ConnectionBlockedEvent connectionBlockedEvent = blockedConnectionEvent.get();
    assertNotNull(connectionBlockedEvent);
    assertEquals("Test connection blocked", connectionBlockedEvent.getReason());
    assertSame(TestUtils.getPropertyValue(connection, "target"), connectionBlockedEvent.getConnection());

    amqConnection.processControlCommand(new AMQCommand(new AMQImpl.Connection.Unblocked()));

    assertTrue(unblockedConnectionLatch.await(10, TimeUnit.SECONDS));

    ConnectionUnblockedEvent connectionUnblockedEvent = unblockedConnectionEvent.get();
    assertNotNull(connectionUnblockedEvent);
    assertSame(TestUtils.getPropertyValue(connection, "target"), connectionUnblockedEvent.getConnection());
}