Example usage for org.springframework.amqp.rabbit.connection RabbitUtils closeChannel

List of usage examples for org.springframework.amqp.rabbit.connection RabbitUtils closeChannel

Introduction

In this page you can find the example usage for org.springframework.amqp.rabbit.connection RabbitUtils closeChannel.

Prototype

public static void closeChannel(@Nullable Channel channel) 

Source Link

Document

Close the given RabbitMQ Channel and ignore any thrown exception.

Usage

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

/**
 * Obtain a RabbitMQ Channel that is synchronized with the current
 * transaction, if any./* w  w  w  . j a  v  a 2s  .  com*/
 * 
 * @param connectionFactory
 *            the RabbitMQ ConnectionFactory to bind for (used as
 *            TransactionSynchronizationManager key)
 * @param resourceFactory
 *            the ResourceFactory to use for extracting or creating RabbitMQ
 *            resources
 * @return the transactional Channel, or <code>null</code> if none found
 */
private static RabbitResourceHolder doGetTransactionalResourceHolder(ConnectionFactory connectionFactory,
        ResourceFactory resourceFactory) {

    Assert.notNull(connectionFactory, "ConnectionFactory must not be null");
    Assert.notNull(resourceFactory, "ResourceFactory must not be null");

    RabbitResourceHolder resourceHolder = (RabbitResourceHolder) TransactionSynchronizationManager
            .getResource(connectionFactory);
    if (resourceHolder != null) {
        Channel channel = resourceFactory.getChannel(resourceHolder);
        if (channel != null) {
            return resourceHolder;
        }
    }
    RabbitResourceHolder resourceHolderToUse = resourceHolder;
    if (resourceHolderToUse == null) {
        resourceHolderToUse = new RabbitResourceHolder();
    }
    Connection connection = resourceFactory.getConnection(resourceHolderToUse);
    Channel channel = null;
    try {
        boolean isExistingCon = (connection != null);
        if (!isExistingCon) {
            connection = resourceFactory.createConnection();
            resourceHolderToUse.addConnection(connection);
        }
        channel = consumerChannel.get();
        if (channel == null) {
            channel = resourceFactory.createChannel(connection);
        }
        if (null != channel && channel.isOpen()) {
            resourceHolderToUse.addChannel(channel, connection);
        }

        if (resourceHolderToUse != resourceHolder) {
            bindResourceToTransaction(resourceHolderToUse, connectionFactory,
                    resourceFactory.isSynchedLocalTransactionAllowed());
        }

        return resourceHolderToUse;

    } catch (IOException ex) {
        RabbitUtils.closeChannel(channel);
        RabbitUtils.closeConnection(connection);
        throw new AmqpIOException(ex);
    }
}

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

public static void releaseResources(RabbitResourceHolder resourceHolder) {
    if (resourceHolder == null || resourceHolder.isSynchronizedWithTransaction()) {
        return;// w  ww. j  av a 2s .c o m
    }
    RabbitUtils.closeChannel(resourceHolder.getChannel());
    RabbitUtils.closeConnection(resourceHolder.getConnection());
}

From source file:org.springframework.amqp.rabbit.listener.BlockingQueueConsumer.java

public void stop() {
    cancelled.set(true);//from   w  w  w.  ja  va  2  s  . com
    if (consumer != null && consumer.getChannel() != null && consumer.getConsumerTag() != null
            && !this.cancelReceived.get()) {
        try {
            RabbitUtils.closeMessageConsumer(consumer.getChannel(), consumer.getConsumerTag(), transactional);
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Error closing consumer", e);
            }
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Closing Rabbit Channel: " + channel);
    }
    RabbitUtils.setPhysicalCloseRequired(true);
    // This one never throws exceptions...
    RabbitUtils.closeChannel(channel);
    deliveryTags.clear();
    retryDeliveryTags.clear();
    consumer = null;
}

From source file:org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer.java

private void doConsumeFromQueue(String queue) {
    if (!isActive()) {
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Consume from queue " + queue + " ignore, container stopping");
        }/*from   w  w  w  .j a v a  2 s  .  c om*/
        return;
    }
    Connection connection = null;
    try {
        connection = getConnectionFactory().createConnection();
    } catch (Exception e) {
        this.consumersToRestart.add(new SimpleConsumer(null, null, queue));
        throw new AmqpConnectException(e);
    }
    Channel channel = null;
    SimpleConsumer consumer = null;
    try {
        channel = connection.createChannel(isChannelTransacted());
        channel.basicQos(getPrefetchCount());
        consumer = new SimpleConsumer(connection, channel, queue);
        channel.queueDeclarePassive(queue);
        consumer.consumerTag = channel.basicConsume(queue, getAcknowledgeMode().isAutoAck(),
                (getConsumerTagStrategy() != null ? getConsumerTagStrategy().createConsumerTag(queue) : ""),
                false, isExclusive(), getConsumerArguments(), consumer);
    } catch (IOException e) {
        if (channel != null) {
            RabbitUtils.closeChannel(channel);
        }
        if (connection != null) {
            RabbitUtils.closeConnection(connection);
        }
        if (e.getCause() instanceof ShutdownSignalException
                && e.getCause().getMessage().contains("in exclusive use")) {
            getExclusiveConsumerExceptionLogger().log(logger, "Exclusive consumer failure", e.getCause());
            publishConsumerFailedEvent("Consumer raised exception, attempting restart", false, e);
        } else if (this.logger.isDebugEnabled()) {
            this.logger.debug("Queue not present or basicConsume failed, scheduling consumer " + consumer
                    + " for restart");
        }
        this.consumersToRestart.add(consumer);
        consumer = null;
    }
    synchronized (this.consumersMonitor) {
        if (consumer != null) {
            this.cancellationLock.add(consumer);
            this.consumers.add(consumer);
            this.consumersByQueue.add(queue, consumer);
            if (this.logger.isInfoEnabled()) {
                this.logger.info(consumer + " started");
            }
        }
    }
}

From source file:org.springframework.integration.amqp.inbound.AmqpMessageSource.java

@Override
protected AbstractIntegrationMessageBuilder<Object> doReceive() {
    Connection connection = this.connectionFactory.createConnection(); // NOSONAR - RabbitUtils
    Channel channel = connection.createChannel(this.transacted);
    try {//from  w  w  w. j  av  a 2  s .  c om
        GetResponse resp = channel.basicGet(this.queue, false);
        if (resp == null) {
            RabbitUtils.closeChannel(channel);
            RabbitUtils.closeConnection(connection);
            return null;
        }
        AcknowledgmentCallback callback = this.ackCallbackFactory
                .createCallback(new AmqpAckInfo(connection, channel, this.transacted, resp));
        MessageProperties messageProperties = this.propertiesConverter.toMessageProperties(resp.getProps(),
                resp.getEnvelope(), StandardCharsets.UTF_8.name());
        messageProperties.setConsumerQueue(this.queue);
        Map<String, Object> headers = this.headerMapper.toHeadersFromRequest(messageProperties);
        org.springframework.amqp.core.Message amqpMessage = new org.springframework.amqp.core.Message(
                resp.getBody(), messageProperties);
        Object payload = this.messageConverter.fromMessage(amqpMessage);
        AbstractIntegrationMessageBuilder<Object> builder = getMessageBuilderFactory().withPayload(payload)
                .copyHeaders(headers)
                .setHeader(IntegrationMessageHeaderAccessor.ACKNOWLEDGMENT_CALLBACK, callback);
        if (this.rawMessageHeader) {
            builder.setHeader(AmqpMessageHeaderErrorMessageStrategy.AMQP_RAW_MESSAGE, amqpMessage);
        }
        return builder;
    } catch (IOException e) {
        RabbitUtils.closeChannel(channel);
        RabbitUtils.closeConnection(connection);
        throw RabbitExceptionTranslator.convertRabbitAccessException(e);
    }
}