Example usage for com.rabbitmq.client Connection getPort

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

Introduction

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

Prototype


int getPort();

Source Link

Document

Retrieve the port number.

Usage

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

License:Apache License

static void connect() {
    try {//from  w w  w.j  av  a 2  s  .c  om

        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.navercorp.pinpoint.plugin.jdk7.rabbitmq.RabbitMQTestRunner.java

License:Apache License

void runPushTest() throws Exception {

    final String message = "hello rabbit mq";

    // producer side
    final Connection producerConnection = connectionFactory.newConnection();
    final Channel producerChannel = producerConnection.createChannel();

    producerChannel.exchangeDeclare(RabbitMQTestConstants.EXCHANGE, "direct", false);
    producerChannel.queueDeclare(RabbitMQTestConstants.QUEUE_PUSH, false, false, false, null);
    producerChannel.queueBind(RabbitMQTestConstants.QUEUE_PUSH, RabbitMQTestConstants.EXCHANGE,
            RabbitMQTestConstants.ROUTING_KEY_PUSH);

    AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
    producerChannel.basicPublish(RabbitMQTestConstants.EXCHANGE, RabbitMQTestConstants.ROUTING_KEY_PUSH, false,
            false, builder.appId("test").build(), message.getBytes());

    producerChannel.close();//from w ww  . ja v a  2 s  . c  o m
    producerConnection.close();

    //comsumer side
    final Connection consumerConnection = connectionFactory.newConnection();
    final Channel consumerChannel = consumerConnection.createChannel();
    final String remoteAddress = consumerConnection.getAddress().getHostAddress() + ":"
            + consumerConnection.getPort();

    consumerChannel.queueDeclare(RabbitMQTestConstants.QUEUE_PUSH, false, false, false, null);

    TestConsumer<String> consumer = new TestConsumer<String>(consumerChannel, MessageConverter.FOR_TEST);
    consumerChannel.basicConsume(RabbitMQTestConstants.QUEUE_PUSH, true, consumer);

    // wait consumer
    Assert.assertEquals(message, consumer.getMessage(10, TimeUnit.SECONDS));

    consumerChannel.close();
    consumerConnection.close();

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    // Wait till all traces are recorded (consumer traces are recorded from another thread)
    awaitAndVerifyTraceCount(verifier, 6, 5000L);

    verifier.printCache();
    Class<?> producerChannelClass = producerChannel.getClass();
    Method channelBasicPublish = producerChannelClass.getDeclaredMethod("basicPublish", String.class,
            String.class, boolean.class, boolean.class, AMQP.BasicProperties.class, byte[].class);
    ExpectedTrace channelBasicPublishTrace = Expectations.event(RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
            channelBasicPublish, // method
            null, // rpc
            remoteAddress, // endPoint
            "exchange-" + RabbitMQTestConstants.EXCHANGE, // destinationId
            Expectations.annotation("rabbitmq.exchange", RabbitMQTestConstants.EXCHANGE),
            Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PUSH));
    ExpectedTrace rabbitMqConsumerInvocationTrace = Expectations.root(RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
            "RabbitMQ Consumer Invocation", // method
            "rabbitmq://exchange=" + RabbitMQTestConstants.EXCHANGE, // rpc
            null, // endPoint (collected but API to retrieve local address is not available in all versions, so skip)
            remoteAddress, // remoteAddress
            Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PUSH));
    Class<?> consumerDispatchClass = Class.forName("com.rabbitmq.client.impl.ConsumerDispatcher");
    Method consumerDispatchHandleDelivery = consumerDispatchClass.getDeclaredMethod("handleDelivery",
            Consumer.class, String.class, Envelope.class, AMQP.BasicProperties.class, byte[].class);
    ExpectedTrace consumerDispatcherHandleDeliveryTrace = Expectations
            .event(RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, consumerDispatchHandleDelivery); // method
    ExpectedTrace asynchronousInvocationTrace = Expectations.event(ServiceType.ASYNC.getName(),
            "Asynchronous Invocation");
    Class<?> consumerClass = consumer.getClass();
    Method consumerHandleDelivery = consumerClass.getDeclaredMethod("handleDelivery", String.class,
            Envelope.class, AMQP.BasicProperties.class, byte[].class);
    ExpectedTrace consumerHandleDeliveryTrace = Expectations
            .event(RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, consumerHandleDelivery);
    Class<?> propagationMarkerClass = PropagationMarker.class;
    Method propagationMarkerMark = propagationMarkerClass.getDeclaredMethod("mark");
    ExpectedTrace markTrace = Expectations.event(ServiceType.INTERNAL_METHOD.getName(), propagationMarkerMark);
    verifier.verifyTrace(channelBasicPublishTrace, rabbitMqConsumerInvocationTrace,
            consumerDispatcherHandleDeliveryTrace, asynchronousInvocationTrace, consumerHandleDeliveryTrace,
            markTrace);
    verifier.verifyTraceCount(0);
}

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

License:Apache License

void runPullTest() throws Exception {

    final String message = "hello rabbit mq";

    // producer side
    final Connection producerConnection = connectionFactory.newConnection();
    final Channel producerChannel = producerConnection.createChannel();

    producerChannel.exchangeDeclare(RabbitMQTestConstants.EXCHANGE, "direct", false);
    producerChannel.queueDeclare(RabbitMQTestConstants.QUEUE_PULL, false, false, false, null);
    producerChannel.queueBind(RabbitMQTestConstants.QUEUE_PULL, RabbitMQTestConstants.EXCHANGE,
            RabbitMQTestConstants.ROUTING_KEY_PULL);

    AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
    producerChannel.basicPublish(RabbitMQTestConstants.EXCHANGE, RabbitMQTestConstants.ROUTING_KEY_PULL, false,
            false, builder.appId("test").build(), message.getBytes());

    producerChannel.close();//from   w  ww . jav  a2s .  c  o m
    producerConnection.close();

    //comsumer side
    final Connection consumerConnection = connectionFactory.newConnection();
    final Channel consumerChannel = consumerConnection.createChannel();
    final String remoteAddress = consumerConnection.getAddress().getHostAddress() + ":"
            + consumerConnection.getPort();

    TestMessagePuller messagePuller = new TestMessagePuller(consumerChannel);
    Assert.assertEquals(message,
            messagePuller.pullMessage(MessageConverter.FOR_TEST, RabbitMQTestConstants.QUEUE_PULL, true));

    consumerChannel.close();
    consumerConnection.close();

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    // Wait till all traces are recorded (consumer traces are recorded from another thread)
    awaitAndVerifyTraceCount(verifier, 5, 5000L);

    verifier.printCache();
    // verify producer traces
    Class<?> producerChannelClass = producerChannel.getClass();
    Method channelBasicPublish = producerChannelClass.getDeclaredMethod("basicPublish", String.class,
            String.class, boolean.class, boolean.class, AMQP.BasicProperties.class, byte[].class);
    ExpectedTrace channelBasicPublishTrace = Expectations.event(RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
            channelBasicPublish, // method
            null, // rpc
            remoteAddress, // endPoint
            "exchange-" + RabbitMQTestConstants.EXCHANGE, // destinationId
            Expectations.annotation("rabbitmq.exchange", RabbitMQTestConstants.EXCHANGE),
            Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PULL));
    ExpectedTrace rabbitMqConsumerInvocationTrace = Expectations.root(RabbitMQTestConstants.RABBITMQ_CLIENT, // serviceType
            "RabbitMQ Consumer Invocation", // method
            "rabbitmq://exchange=" + RabbitMQTestConstants.EXCHANGE, // rpc
            null, // endPoint (collected but API to retrieve local address is not available in all versions, so skip)
            remoteAddress, // remoteAddress
            Expectations.annotation("rabbitmq.routingkey", RabbitMQTestConstants.ROUTING_KEY_PULL));
    Class<?> amqChannelClass = Class.forName("com.rabbitmq.client.impl.AMQChannel");
    Method handleCompleteInboundCommand = amqChannelClass.getDeclaredMethod("handleCompleteInboundCommand",
            AMQCommand.class);
    ExpectedTrace handleCompleteInboundCommandTrace = Expectations.event(
            RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL, // serviceType
            handleCompleteInboundCommand); // method
    verifier.verifyDiscreteTrace(channelBasicPublishTrace, rabbitMqConsumerInvocationTrace,
            handleCompleteInboundCommandTrace);

    // verify consumer traces
    Class<?> consumerChannelClass = consumerChannel.getClass();
    Method channelBasicGet = consumerChannelClass.getDeclaredMethod("basicGet", String.class, boolean.class);
    ExpectedTrace channelBasicGetTrace = Expectations.event(RabbitMQTestConstants.RABBITMQ_CLIENT_INTERNAL,
            channelBasicGet);
    Class<?> propagationMarkerClass = PropagationMarker.class;
    Method propagationMarkerMark = propagationMarkerClass.getDeclaredMethod("mark");
    ExpectedTrace markTrace = Expectations.event(ServiceType.INTERNAL_METHOD.getName(), propagationMarkerMark);
    verifier.verifyDiscreteTrace(channelBasicGetTrace, markTrace);
    verifier.verifyTraceCount(0);
}

From source file:com.springsource.insight.plugin.rabbitmqClient.AbstractRabbitMQCollectionAspect.java

License:Apache License

protected void applyConnectionData(Operation op, Connection conn) {
    String connectionUrl = null;//from w  w w . j  a  v  a  2s . com

    if (conn instanceof AMQConnection) {
        connectionUrl = conn.toString();
    } else {
        InetAddress address = conn.getAddress();
        int port = conn.getPort();

        StringBuilder sb = new StringBuilder("amqp://");
        sb.append(address.getHostAddress()).append(":").append(port);

        connectionUrl = sb.toString();
    }

    op.put("host", conn.getAddress().getHostAddress());
    op.put("port", conn.getPort());
    op.put("connectionUrl", connectionUrl);

    //try to extract server version
    String version = getVersion(conn.getServerProperties());
    op.put("serverVersion", version);

    //try to extract client version
    version = getVersion(conn.getClientProperties());
    op.put("clientVersion", version);
}