Example usage for com.rabbitmq.client Channel getConnection

List of usage examples for com.rabbitmq.client Channel getConnection

Introduction

In this page you can find the example usage for com.rabbitmq.client Channel getConnection.

Prototype

Connection getConnection();

Source Link

Document

Retrieve the connection which carries this channel.

Usage

From source file:org.mule.transport.amqp.internal.client.ChannelHandler.java

License:Open Source License

public Channel getTransactedResourceChannel(ImmutableEndpoint endpoint)
        throws IOException, TransactionException {
    final byte action = endpoint.getTransactionConfig().getAction();

    final boolean mayUseChannelFromTransaction = action == TransactionConfig.ACTION_BEGIN_OR_JOIN
            || action == TransactionConfig.ACTION_JOIN_IF_POSSIBLE
            || action == TransactionConfig.ACTION_INDIFFERENT;

    final boolean mustUseChannelFromTransaction = action == TransactionConfig.ACTION_ALWAYS_JOIN;

    final Transaction transaction = TransactionCoordination.getInstance().getTransaction();
    if (transaction instanceof AmqpTransaction) {
        if (mustUseChannelFromTransaction || mayUseChannelFromTransaction) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Using transacted channel from current transaction: " + transaction);
            }//from  w ww  .j  a v a  2s.  c  o  m

            return ((AmqpTransaction) transaction).getTransactedChannel();
        }
    } else if (transaction instanceof DelegateTransaction) {
        // we can't use the current endpoint channel because it may get closed (if the
        // endpoint instance is destroyed) while the transaction block is not done with...
        final Channel channel = createChannel(endpoint);
        channel.txSelect();
        // we wrap the channel so the transaction will know it can safely close it an
        // commit/rollback
        transaction.bindResource(channel.getConnection(), new CloseableChannelWrapper(channel));

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Created transacted channel for delegate transaction: " + transaction);
        }

        return channel;
    } else {
        if (mustUseChannelFromTransaction) {
            throw new IllegalTransactionStateException(MessageFactory
                    .createStaticMessage("No active AMQP transaction found for endpoint: " + endpoint));
        }
    }

    return null;
}

From source file:org.springframework.amqp.rabbit.connection.CachingConnectionFactoryIntegrationTests.java

License:Apache License

@Test
public void testHardErrorAndReconnect() throws Exception {

    RabbitTemplate template = new RabbitTemplate(connectionFactory);
    RabbitAdmin admin = new RabbitAdmin(connectionFactory);
    Queue queue = new Queue("foo");
    admin.declareQueue(queue);/*from  www  . ja v a  2 s.  c om*/
    final String route = queue.getName();

    final CountDownLatch latch = new CountDownLatch(1);
    try {
        template.execute(new ChannelCallback<Object>() {
            @Override
            public Object doInRabbit(Channel channel) throws Exception {
                channel.getConnection().addShutdownListener(new ShutdownListener() {
                    @Override
                    public void shutdownCompleted(ShutdownSignalException cause) {
                        logger.info("Error", cause);
                        latch.countDown();
                        // This will be thrown on the Connection thread just before it dies, so basically ignored
                        throw new RuntimeException(cause);
                    }
                });
                String tag = channel.basicConsume(route, new DefaultConsumer(channel));
                // Consume twice with the same tag is a hard error (connection will be reset)
                String result = channel.basicConsume(route, false, tag, new DefaultConsumer(channel));
                fail("Expected IOException, got: " + result);
                return null;
            }
        });
        fail("Expected AmqpIOException");
    } catch (AmqpIOException e) {
        // expected
    }
    template.convertAndSend(route, "message");
    assertTrue(latch.await(1000, TimeUnit.MILLISECONDS));
    String result = (String) template.receiveAndConvert(route);
    assertEquals("message", result);
    result = (String) template.receiveAndConvert(route);
    assertEquals(null, result);
}

From source file:org.springframework.boot.actuate.health.RabbitHealthIndicator.java

License:Apache License

private String getVersion() {
    return this.rabbitTemplate.execute(new ChannelCallback<String>() {
        @Override//from w w w. j av  a  2s.  c  o  m
        public String doInRabbit(Channel channel) throws Exception {
            Map<String, Object> serverProperties = channel.getConnection().getServerProperties();
            return serverProperties.get("version").toString();
        }
    });
}

From source file:org.wso2.siddhi.debs2017.input.DebsBenchmarkSystem.java

License:Open Source License

@Override
public void close() {

    try {/*from   w w w. j av  a  2 s  .  co  m*/
        super.close();
        Channel channel = inputQueue.getChannel();
        Connection connection = channel.getConnection();
        channel.close();
        connection.close();
        channel = outputQueue.getChannel();
        connection = channel.getConnection();
        channel.close();
        connection.close();
    } catch (Exception e) {
        logger.debug("Exception", e);
    }
}

From source file:play.modules.rabbitmq.consumer.RabbitMQConsumer.java

License:Apache License

/**
 * Go get her son.//from www .j a  va2  s  .  c om
 */
private void goGetHerSon() {
    // Get Plugin
    RabbitMQPlugin plugin = Play.plugin(RabbitMQPlugin.class);

    // Define Channel
    Channel channel = null;
    QueueingConsumer consumer = null;
    Long deliveryTag = null;

    // Get Channel
    while (true) {
        // Log Debug
        Logger.info("Entering main loop on consumer: " + this);

        // Are Consumers Running?
        boolean active = RabbitMQPlugin.areConsumersActive();

        // Only do work if consumers are running
        if (active) {
            try {
                // Create Channel
                if (channel == null || (channel != null && channel.isOpen() == false)) {
                    consumer = null;
                    channel = this.createChannel(plugin);
                }

                // Create Consumer
                if (consumer == null) {
                    consumer = this.createConsumer(channel, plugin);
                }

                // Get Task
                QueueingConsumer.Delivery task = consumer.nextDelivery();

                // Date Night
                if ((task != null) && (task.getBody() != null)) {
                    try {
                        // Fire job that will pass the message to the
                        // consumer,
                        // ack the queue and do the retry logic
                        deliveryTag = task.getEnvelope().getDeliveryTag();
                        T message = this.toObject(task.getBody());
                        new RabbitMQMessageConsumerJob(channel, deliveryTag, this.queue(), this, message,
                                this.retries()).doJobWithResult();

                    } catch (Throwable t) {
                        // Handle Exception
                        Logger.error(ExceptionUtil.getStackTrace(t));
                    }

                }

            } catch (Throwable t) {
                Logger.error(
                        "Error creating consumer channel to RabbitMQ, retrying in a few seconds. Exception: %s",
                        ExceptionUtil.getStackTrace(t));
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    Logger.error(ExceptionUtil.getStackTrace(t));
                }

            } finally {
                if (channel != null) {
                    // Now tell Daddy everything is cool
                    try {
                        if (deliveryTag != null && channel.isOpen()) {
                            channel.basicAck(deliveryTag, false);
                        }
                    } catch (Throwable e) {
                        Logger.error(ExceptionUtil
                                .getStackTrace("Error doing a basicAck for tag: " + deliveryTag, e));
                    }
                    try {
                        if (channel.getConnection() != null && channel.getConnection().isOpen()) {
                            channel.getConnection().close();
                        }
                        if (channel.isOpen() == true) {
                            channel.close();
                        }
                    } catch (Throwable t) {
                        Logger.error(ExceptionUtil.getStackTrace(t));
                    } finally {
                        channel = null;
                    }
                }
            }
        } else {
            Logger.warn("RabbitMQ consumers are paused and napping for 10 secs...");
            try {
                Thread.sleep(10000);
            } catch (Throwable t) {
            }
        }
    }
}

From source file:reactor.rabbitmq.LazyChannelPoolTests.java

License:Open Source License

private Channel channel(int channelNumber) {
    Channel channel = mock(Channel.class);
    when(channel.getChannelNumber()).thenReturn(channelNumber);
    when(channel.isOpen()).thenReturn(true);
    when(channel.getConnection()).thenReturn(connection);
    return channel;
}

From source file:reactor.rabbitmq.RabbitFluxTests.java

License:Open Source License

@Test
public void publishConfirmsErrorWhilePublishing() throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    Channel mockChannel = mock(Channel.class);
    when(mockConnectionFactory.newConnection()).thenReturn(mockConnection);
    when(mockConnection.createChannel()).thenReturn(mockChannel);
    when(mockConnection.isOpen()).thenReturn(true);
    when(mockChannel.getConnection()).thenReturn(mockConnection);

    AtomicLong publishSequence = new AtomicLong();
    when(mockChannel.getNextPublishSeqNo()).thenAnswer(invocation -> publishSequence.incrementAndGet());
    when(mockChannel.isOpen()).thenReturn(true);

    CountDownLatch channelCloseLatch = new CountDownLatch(1);
    doAnswer(answer -> {//from   w w  w. j a  v a  2 s .co m
        channelCloseLatch.countDown();
        return null;
    }).when(mockChannel).close();

    CountDownLatch serverPublishConfirmLatch = new CountDownLatch(1);
    doNothing().doAnswer(answer -> {
        // see https://github.com/reactor/reactor-rabbitmq/pull/67#issuecomment-472789735
        serverPublishConfirmLatch.await(5, TimeUnit.SECONDS);
        throw new IOException("simulated error while publishing");
    }).when(mockChannel).basicPublish(anyString(), anyString(), nullable(AMQP.BasicProperties.class),
            any(byte[].class));

    int nbMessages = 10;
    Flux<OutboundMessage> msgFlux = Flux.range(0, nbMessages)
            .map(i -> new OutboundMessage("", queue, "".getBytes()));
    int nbMessagesAckNack = 1 + 1; // first published message confirmed + "fake" confirmation because of sending failure
    CountDownLatch confirmLatch = new CountDownLatch(nbMessagesAckNack);
    sender = createSender(new SenderOptions().connectionFactory(mockConnectionFactory));
    sender.sendWithPublishConfirms(msgFlux, new SendOptions().exceptionHandler((ctx, e) -> {
        throw new RabbitFluxException(e);
    })).subscribe(outboundMessageResult -> {
        if (outboundMessageResult.getOutboundMessage() != null) {
            confirmLatch.countDown();
        }
    }, error -> {
    });

    // have to wait a bit the subscription propagates and add the confirm listener
    Thread.sleep(100L);

    ArgumentCaptor<ConfirmListener> confirmListenerArgumentCaptor = ArgumentCaptor
            .forClass(ConfirmListener.class);
    verify(mockChannel).addConfirmListener(confirmListenerArgumentCaptor.capture());
    ConfirmListener confirmListener = confirmListenerArgumentCaptor.getValue();

    ExecutorService ioExecutor = Executors.newSingleThreadExecutor();
    ioExecutor.submit(() -> {
        confirmListener.handleAck(1, false);
        serverPublishConfirmLatch.countDown();
        return null;
    });

    assertTrue(confirmLatch.await(1L, TimeUnit.SECONDS));
    assertTrue(channelCloseLatch.await(1L, TimeUnit.SECONDS));
    verify(mockChannel, times(1)).close();
}

From source file:reactor.rabbitmq.Receiver.java

License:Open Source License

public Flux<Delivery> consumeNoAck(final String queue, ReceiverOptions options) {
    // TODO track flux so it can be disposed when the sender is closed?
    // could be also developer responsibility
    return Flux.create(emitter -> {
        connectionMono.subscribe(connection -> {
            try {
                // TODO handle exception
                Channel channel = connection.createChannel();
                final DefaultConsumer consumer = new DefaultConsumer(channel) {
                    @Override/*from  www  .  j  a  va  2s.  co  m*/
                    public void handleDelivery(String consumerTag, Envelope envelope,
                            AMQP.BasicProperties properties, byte[] body) throws IOException {
                        emitter.next(new Delivery(envelope, properties, body));
                    }

                    @Override
                    public void handleCancel(String consumerTag) throws IOException {
                        LOGGER.warn("Flux consumer {} has been cancelled", consumerTag);
                    }
                };
                final String consumerTag = channel.basicConsume(queue, true, consumer);
                emitter.onDispose(() -> {
                    try {
                        if (channel.isOpen() && channel.getConnection().isOpen()) {
                            channel.basicCancel(consumerTag);
                            channel.close();
                        }
                    } catch (TimeoutException | IOException e) {
                        throw new ReactorRabbitMqException(e);
                    }
                });
            } catch (IOException e) {
                throw new ReactorRabbitMqException(e);
            }
        });

    }, options.getOverflowStrategy());
}

From source file:reactor.rabbitmq.Receiver.java

License:Open Source License

public Flux<AcknowledgableDelivery> consumeManuelAck(final String queue, ReceiverOptions options) {
    // TODO track flux so it can be disposed when the sender is closed?
    // could be also developer responsibility
    return Flux.create(emitter -> {
        connectionMono.subscribe(connection -> {
            try {

                Channel channel = connection.createChannel();
                if (options.getQos() != 0) {
                    channel.basicQos(options.getQos());
                }//from  ww  w  .  ja v a2s  .co  m
                final DefaultConsumer consumer = new DefaultConsumer(channel) {
                    @Override
                    public void handleDelivery(String consumerTag, Envelope envelope,
                            AMQP.BasicProperties properties, byte[] body) throws IOException {
                        AcknowledgableDelivery message = new AcknowledgableDelivery(envelope, properties, body,
                                getChannel());
                        if (options.getHookBeforeEmit().apply(emitter, message)) {
                            emitter.next(message);
                        }
                    }
                };
                final String consumerTag = channel.basicConsume(queue, false, consumer);
                emitter.onDispose(() -> {

                    try {
                        if (channel.isOpen() && channel.getConnection().isOpen()) {
                            channel.basicCancel(consumerTag);
                            channel.close();
                        }
                    } catch (TimeoutException | IOException e) {
                        throw new ReactorRabbitMqException(e);
                    }
                });
            } catch (IOException e) {
                throw new ReactorRabbitMqException(e);
            }
        });
    }, options.getOverflowStrategy());
}