Example usage for com.rabbitmq.client Channel confirmSelect

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

Introduction

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

Prototype

Confirm.SelectOk confirmSelect() throws IOException;

Source Link

Document

Enables publisher acknowledgements on this channel.

Usage

From source file:org.axonframework.amqp.eventhandling.spring.SpringAMQPPublisher.java

License:Apache License

/**
 * Sends the given {@code events} to the configured AMQP Exchange. It takes the current Unit of Work into account
 * when available. Otherwise, it simply publishes directly.
 *
 * @param events the events to publish on the AMQP Message Broker
 *///from   ww  w.ja  v  a  2s.co  m
protected void send(List<? extends EventMessage<?>> events) {
    Channel channel = connectionFactory.createConnection().createChannel(isTransactional);
    try {
        if (isTransactional) {
            channel.txSelect();
        } else if (waitForAck) {
            channel.confirmSelect();
        }
        for (EventMessage event : events) {
            AMQPMessage amqpMessage = messageConverter.createAMQPMessage(event);
            doSendMessage(channel, amqpMessage);
        }
        if (CurrentUnitOfWork.isStarted()) {
            UnitOfWork<?> unitOfWork = CurrentUnitOfWork.get();
            unitOfWork.onCommit(u -> {
                if ((isTransactional || waitForAck) && !channel.isOpen()) {
                    throw new EventPublicationFailedException(
                            "Unable to Commit UnitOfWork changes to AMQP: Channel is closed.",
                            channel.getCloseReason());
                }
            });
            unitOfWork.afterCommit(u -> {
                try {
                    if (isTransactional) {
                        channel.txCommit();
                    } else if (waitForAck) {
                        try {
                            channel.waitForConfirmsOrDie(publisherAckTimeout);
                        } catch (IOException ex) {
                            throw new EventPublicationFailedException(
                                    "Failed to receive acknowledgements for all events", ex);
                        } catch (TimeoutException ex) {
                            throw new EventPublicationFailedException(
                                    "Timeout while waiting for publisher acknowledgements", ex);
                        }
                    }
                } catch (IOException e) {
                    logger.warn("Unable to commit transaction on channel.", e);
                } catch (InterruptedException e) {
                    logger.warn("Interrupt received when waiting for message confirms.");
                    Thread.currentThread().interrupt();
                }
                tryClose(channel);
            });
            unitOfWork.onRollback(u -> {
                try {
                    if (isTransactional) {
                        channel.txRollback();
                    }
                } catch (IOException ex) {
                    logger.warn("Unable to rollback transaction on channel.", ex);
                }
                tryClose(channel);
            });
        } else if (isTransactional) {
            channel.txCommit();
        } else if (waitForAck) {
            channel.waitForConfirmsOrDie();
        }
    } catch (IOException e) {
        if (isTransactional) {
            tryRollback(channel);
        }
        throw new EventPublicationFailedException("Failed to dispatch Events to the Message Broker.", e);
    } catch (ShutdownSignalException e) {
        throw new EventPublicationFailedException("Failed to dispatch Events to the Message Broker.", e);
    } catch (InterruptedException e) {
        logger.warn("Interrupt received when waiting for message confirms.");
        Thread.currentThread().interrupt();
    } finally {
        if (!CurrentUnitOfWork.isStarted()) {
            tryClose(channel);
        }
    }
}

From source file:org.axonframework.eventhandling.amqp.RabbitMQBenchmark.java

License:Apache License

public static void main(String[] args) throws IOException, InterruptedException {
    final Connection connection = new ConnectionFactory().newConnection();
    final Channel channel = connection.createChannel();
    String queueName = channel.queueDeclare().getQueue();
    execute("Transactional and Channel pooling", createChannelPoolSharingThreads(connection, queueName));
    queueName = refreshQueue(channel, queueName);
    execute("Transactional, new Channel per tx", createChannelCreatingThreads(connection, queueName, true));
    queueName = refreshQueue(channel, queueName);
    execute("Non-transactional, new Channel per tx",
            createChannelCreatingThreads(connection, queueName, false));
    queueName = refreshQueue(channel, queueName);
    execute("Non-transactional, single Channel", createChannelSharingThreads(connection, queueName));
    channel.confirmSelect();
    connection.close();//from   www.  j av a2s  .c om
}

From source file:org.axonframework.eventhandling.amqp.spring.SpringAMQPEventBus.java

License:Apache License

@Override
protected void prepareCommit(List<? extends EventMessage<?>> events) {
    Channel channel = connectionFactory.createConnection().createChannel(isTransactional);
    try {/*  ww  w .j ava  2 s. c o  m*/
        if (isTransactional) {
            channel.txSelect();
        } else if (waitForAck) {
            channel.confirmSelect();
        }
        for (EventMessage event : events) {
            AMQPMessage amqpMessage = messageConverter.createAMQPMessage(event);
            doSendMessage(channel, amqpMessage);
        }
        if (CurrentUnitOfWork.isStarted()) {
            CurrentUnitOfWork.get().onCommit(u -> {
                if ((isTransactional || waitForAck) && !channel.isOpen()) {
                    throw new EventPublicationFailedException(
                            "Unable to Commit UnitOfWork changes to AMQP: Channel is closed.",
                            channel.getCloseReason());
                }
            });
            CurrentUnitOfWork.get().afterCommit(u -> {
                try {
                    if (isTransactional) {
                        channel.txCommit();
                    } else if (waitForAck) {
                        try {
                            channel.waitForConfirmsOrDie(publisherAckTimeout);
                        } catch (IOException ex) {
                            throw new EventPublicationFailedException(
                                    "Failed to receive acknowledgements for all events", ex);
                        } catch (TimeoutException ex) {
                            throw new EventPublicationFailedException(
                                    "Timeout while waiting for publisher acknowledgements", ex);
                        }
                    }
                } catch (IOException e) {
                    logger.warn("Unable to commit transaction on channel.", e);
                } catch (InterruptedException e) {
                    logger.warn("Interrupt received when waiting for message confirms.");
                    Thread.currentThread().interrupt();
                }
                tryClose(channel);
            });
            CurrentUnitOfWork.get().onRollback(u -> {
                try {
                    if (isTransactional) {
                        channel.txRollback();
                    }
                } catch (IOException ex) {
                    logger.warn("Unable to rollback transaction on channel.", ex);
                }
                tryClose(channel);
            });
        } else if (isTransactional) {
            channel.txCommit();
        } else if (waitForAck) {
            channel.waitForConfirmsOrDie();
        }
    } catch (IOException e) {
        if (isTransactional) {
            tryRollback(channel);
        }
        throw new EventPublicationFailedException("Failed to dispatch Events to the Message Broker.", e);
    } catch (ShutdownSignalException e) {
        throw new EventPublicationFailedException("Failed to dispatch Events to the Message Broker.", e);
    } catch (InterruptedException e) {
        logger.warn("Interrupt received when waiting for message confirms.");
        Thread.currentThread().interrupt();
    } finally {
        if (!CurrentUnitOfWork.isStarted()) {
            tryClose(channel);
        }
    }
}

From source file:org.axonframework.eventhandling.amqp.spring.SpringAMQPTerminal.java

License:Apache License

@Override
public void publish(EventMessage... events) {
    final Channel channel = connectionFactory.createConnection().createChannel(isTransactional);
    try {//w  w w  .  j av  a 2 s .co  m
        if (waitForAck) {
            channel.confirmSelect();
        }
        for (EventMessage event : events) {
            AMQPMessage amqpMessage = messageConverter.createAMQPMessage(event);
            doSendMessage(channel, amqpMessage);
        }
        if (CurrentUnitOfWork.isStarted()) {
            CurrentUnitOfWork.get().registerListener(new ChannelTransactionUnitOfWorkListener(channel));
        } else if (isTransactional) {
            channel.txCommit();
        } else if (waitForAck) {
            channel.waitForConfirmsOrDie();
        }
    } catch (IOException e) {
        if (isTransactional) {
            tryRollback(channel);
        }
        throw new EventPublicationFailedException("Failed to dispatch Events to the Message Broker.", e);
    } catch (ShutdownSignalException e) {
        throw new EventPublicationFailedException("Failed to dispatch Events to the Message Broker.", e);
    } catch (InterruptedException e) {
        logger.warn("Interrupt received when waiting for message confirms.");
        Thread.currentThread().interrupt();
    } finally {
        if (!CurrentUnitOfWork.isStarted()) {
            tryClose(channel);
        }
    }
}

From source file:org.mule.transport.amqp.DefaultAmqpConfirmsManager.java

License:Open Source License

public void requestConfirm(Channel channel, MuleEvent event) throws Exception {
    if (!handlesConfirms()) {
        return;/*from   w  w w  . j  av a  2s  .  c om*/
    }

    channel.addConfirmListener(new ConfirmListener() {
        public void handleAck(long deliveryTag, boolean multiple) throws IOException {
            confirm(deliveryTag, true);
        }

        public void handleNack(long deliveryTag, boolean multiple) throws IOException {
            confirm(deliveryTag, false);
        }
    });

    channel.confirmSelect();
    long nextSequence = channel.getNextPublishSeqNo();
    pendingConfirms.put(nextSequence, new ConfirmHandler());
    event.setFlowVariable(AmqpConstants.NEXT_PUBLISH_SEQ_NO, nextSequence);

}

From source file:org.mule.transport.amqp.internal.confirm.DefaultConfirmsManager.java

License:Open Source License

public void requestConfirm(Channel channel, MuleEvent event) throws Exception {
    if (!handlesConfirms()) {
        return;/*from  w  w w  .ja  va 2s.  c  o  m*/
    }

    channel.addConfirmListener(new ConfirmListener() {
        public void handleAck(long deliveryTag, boolean multiple) throws IOException {
            confirm(deliveryTag, true);
        }

        public void handleNack(long deliveryTag, boolean multiple) throws IOException {
            confirm(deliveryTag, false);
        }
    });

    channel.confirmSelect();
    long nextSequence = channel.getNextPublishSeqNo();
    pendingConfirms.put(nextSequence, new ConfirmHandler());
    event.setFlowVariable(AmqpConnector.MESSAGE_PROPERTY_NEXT_PUBLISH_SEQ_NO, nextSequence);

}

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

License:Apache License

private Channel doCreateBareChannel(ChannelCachingConnectionProxy connection, boolean transactional) {
    Channel channel = connection.createBareChannel(transactional);
    if (this.publisherConfirms) {
        try {/*from ww  w .j  a v  a  2s  .  co m*/
            channel.confirmSelect();
        } catch (IOException e) {
            logger.error("Could not configure the channel to receive publisher confirms", e);
        }
    }
    if (this.publisherConfirms || this.publisherReturns) {
        if (!(channel instanceof PublisherCallbackChannelImpl)) {
            channel = new PublisherCallbackChannelImpl(channel);
        }
    }
    if (channel != null) {
        channel.addShutdownListener(this);
    }
    return channel;
}

From source file:reactor.rabbitmq.Sender.java

License:Open Source License

public Flux<OutboundMessageResult> sendWithPublishConfirms(Publisher<OutboundMessage> messages) {
    // TODO using a pool of channels?
    // would be much more efficient if send is called very often
    // less useful if seldom called, only for long or infinite message flux
    final Mono<Channel> channelMono = connectionMono.flatMap(connection -> {
        Channel channel = null;
        try {/*  w w  w.  jav  a2  s .  c  om*/
            channel = connection.createChannel();
            channel.confirmSelect();
            return Mono.just(channel);
        } catch (IOException e) {
            return Mono.error(e);
        }
    });

    return channelMono.flatMapMany(channel -> new Flux<OutboundMessageResult>() {
        @Override
        public void subscribe(Subscriber<? super OutboundMessageResult> subscriber) {
            messages.subscribe(new PublishConfirmSubscriber(channel, subscriber));
        }
    });
}

From source file:uk.ac.sanger.cgp.wwdocker.messages.Messaging.java

License:Open Source License

/**
 * Sends a message to the specified queue
 * @param queue/*www.  j  a  v  a  2s . c  o m*/
 * @param in
 * @param host
 * @throws IOException
 * @throws InterruptedException 
 * @throws TimeoutException
 */
public void sendMessage(String queue, Object in, String host)
        throws IOException, InterruptedException, TimeoutException {
    String message;
    Builder propBuilder = MessageProperties.MINIMAL_PERSISTENT_BASIC.builder();
    if (in.getClass().equals(String.class)) {
        message = (String) in;
    } else {
        message = Utils.objectToJson(in);
        if (in.getClass().equals(WorkerState.class)) {
            host = ((WorkerState) in).getResource().getHostName();
        }
    }
    if (host != null) {
        Map<String, Object> headers = new HashMap();
        headers.put("host", host);
        propBuilder.headers(headers);
    }
    BasicProperties mProp = propBuilder.build();

    Connection connectionSend = getRmqConn();
    Channel channel = connectionSend.createChannel();
    channel.confirmSelect();
    channel.queueDeclare(queue, true, false, false, null);
    channel.basicPublish("", queue, mProp, message.getBytes());
    channel.waitForConfirmsOrDie(5000);
    logger.info(queue + " sent: " + message);
    channel.close();
    closeRmqConn(connectionSend);
}

From source file:uk.ac.sanger.cgp.wwdocker.messages.Messaging.java

License:Open Source License

public void sendFile(String queue, String host, File f)
        throws IOException, InterruptedException, TimeoutException {
    Map<String, Object> headers = new HashMap();
    headers.put("host", host);
    BasicProperties mProp = MessageProperties.MINIMAL_PERSISTENT_BASIC.builder().headers(headers).build();
    Connection connectionSend = getRmqConn();
    Channel channel = connectionSend.createChannel();
    channel.confirmSelect();
    channel.queueDeclare(queue, true, false, false, null);
    channel.basicPublish("", queue, mProp, Files.readAllBytes(f.toPath()));
    channel.waitForConfirmsOrDie(5000);/*ww w . j ava 2 s.c  o  m*/
    logger.info(queue + " file: " + f.getAbsolutePath());
    channel.close();
    closeRmqConn(connectionSend);
}