List of usage examples for com.rabbitmq.client Channel basicAck
void basicAck(long deliveryTag, boolean multiple) throws IOException;
From source file:org.mule.transport.amqp.internal.client.MessageConsumer.java
License:Open Source License
public AmqpMessage consumeMessage(final Channel channel, final String queue, final boolean autoAck, final long timeout) throws IOException, InterruptedException { final long startTime = System.currentTimeMillis(); // try first with a basic get to potentially quickly retrieve a pending message final GetResponse getResponse = channel.basicGet(queue, autoAck); // if timeout is zero or if a message has been fetched don't go any further if ((timeout == 0) || (getResponse != null)) { return getResponse == null ? null : new AmqpMessage(null, getResponse.getEnvelope(), getResponse.getProps(), getResponse.getBody()); }/*from w ww . j a va2 s . c om*/ // account for the time taken to perform the basic get final long elapsedTime = System.currentTimeMillis() - startTime; final long actualTimeOut = timeout - elapsedTime; if (actualTimeOut < 0) { return null; } final QueueingConsumer consumer = new SingleMessageQueueingConsumer(channel); // false -> no AMQP-level autoAck with the SingleMessageQueueingConsumer final String consumerTag = channel.basicConsume(queue, false, consumer); try { final QueueingConsumer.Delivery delivery = consumer.nextDelivery(actualTimeOut); if (delivery == null) { return null; } else { if (autoAck) { // ack only if auto-ack was requested, otherwise it's up to the caller to ack channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } return new AmqpMessage(consumerTag, delivery.getEnvelope(), delivery.getProperties(), delivery.getBody()); } } finally { try { channel.basicCancel(consumerTag); } catch (IOException e) { /** * The broker could decide to cancel a subscription on certain situations */ if (LOGGER.isDebugEnabled()) { LOGGER.debug("Subscription to channel with consumerTag " + StringUtils.defaultString(consumerTag) + " could not be closed.", e); } } } }
From source file:org.mule.transport.amqp.internal.client.MessagePropertiesHandler.java
License:Open Source License
public void ackMessageIfNecessary(final Channel channel, final AmqpMessage amqpMessage, final ImmutableEndpoint endpoint) throws IOException { AmqpConnector connector = (AmqpConnector) endpoint.getConnector(); if ((endpoint.getTransactionConfig().isTransacted()) || (connector.getAckMode() != AckMode.MULE_AUTO)) { return;/*from w ww. j ava2s . c o m*/ } channel.basicAck(amqpMessage.getEnvelope().getDeliveryTag(), false); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Mule acknowledged message: " + amqpMessage + " on channel: " + channel); } }
From source file:org.mule.transport.amqp.internal.processor.Acknowledger.java
License:Open Source License
public void ack(final MuleMessage message, final boolean multiple) throws MuleException { final Long deliveryTag = getDeliveryTagOrFail(message, CHANNEL_ACTION); final Channel channel = getChannelOrFail(message, CHANNEL_ACTION); try {// www . j a v a 2 s. c o m channel.basicAck(deliveryTag, multiple); } catch (final Exception e) { throw new DefaultMuleException( "Failed to ack message w/deliveryTag: " + deliveryTag + " on channel: " + channel, e); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Manually acknowledged message w/deliveryTag: " + deliveryTag + " on channel: " + channel); } }
From source file:org.ninjav.rabbitmq.TestReceive.java
@Test public void canReceiveMessageFromQueue() throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); Consumer consumer;//from ww w .j a va2s .c o m consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { try { String message = new String(body, "UTF-8"); System.out.println("Message Received: " + message); } finally { channel.basicAck(envelope.getDeliveryTag(), false); } } }; boolean autoAck = false; channel.basicConsume(QUEUE_NAME, autoAck, consumer); try { Thread.sleep(100000); } catch (InterruptedException ex) { Logger.getLogger(TestReceive.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.sdw.scheduler.QueueProcessor.java
License:Apache License
/** * Implementation of the Runnable interface's run method * Polls for messages in the shared queue and logs the results on arrival of message *//*from w w w . j a v a 2 s .c om*/ @Override public void run() { try { ConnectionFactory factory = new ConnectionFactory(); factory.setUri(System.getenv("CLOUDAMQP_URL")); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); String queueName = "work-queue-1"; Map<String, Object> params = new HashMap<>(); params.put("x-ha-policy", "all"); channel.queueDeclare(queueName, true, false, false, params); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, false, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); if (delivery != null) { String msg = new String(delivery.getBody(), "UTF-8"); LOG.info("Message Received: " + msg); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } } catch (IOException | KeyManagementException | NoSuchAlgorithmException | URISyntaxException | ShutdownSignalException | ConsumerCancelledException | InterruptedException ex) { LOG.error(ex.getMessage(), ex); } }
From source file:org.springframework.amqp.rabbit.connection.RabbitResourceHolder.java
License:Apache License
public void commitAll() throws AmqpException { try {// w w w . j av a 2 s. com for (Channel channel : this.channels) { if (deliveryTags.containsKey(channel)) { for (Long deliveryTag : deliveryTags.get(channel)) { channel.basicAck(deliveryTag, false); } } channel.txCommit(); } } catch (IOException e) { throw new AmqpException("failed to commit RabbitMQ transaction", e); } }
From source file:org.springframework.amqp.rabbit.core.RabbitTemplate.java
License:Apache License
@Override public Message receive(final String queueName) { return execute(new ChannelCallback<Message>() { @Override//from w w w .j a v a 2 s. c o m public Message doInRabbit(Channel channel) throws IOException { GetResponse response = channel.basicGet(queueName, !isChannelTransacted()); // Response can be null is the case that there is no message on the queue. if (response != null) { long deliveryTag = response.getEnvelope().getDeliveryTag(); if (isChannelLocallyTransacted(channel)) { channel.basicAck(deliveryTag, false); channel.txCommit(); } else if (isChannelTransacted()) { // Not locally transacted but it is transacted so it // could be synchronized with an external transaction ConnectionFactoryUtils.registerDeliveryTag(getConnectionFactory(), channel, deliveryTag); } return RabbitTemplate.this.buildMessageFromResponse(response); } return null; } }); }
From source file:org.springframework.amqp.rabbit.core.RabbitTemplate.java
License:Apache License
@SuppressWarnings("unchecked") private <R, S> boolean doReceiveAndReply(final String queueName, final ReceiveAndReplyCallback<R, S> callback, final ReplyToAddressCallback<S> replyToAddressCallback) throws AmqpException { return this.execute(new ChannelCallback<Boolean>() { @Override/*from w ww. j av a 2 s. c o m*/ public Boolean doInRabbit(Channel channel) throws Exception { boolean channelTransacted = RabbitTemplate.this.isChannelTransacted(); GetResponse response = channel.basicGet(queueName, !channelTransacted); // Response can be null in the case that there is no message on the queue. if (response != null) { long deliveryTag = response.getEnvelope().getDeliveryTag(); boolean channelLocallyTransacted = RabbitTemplate.this.isChannelLocallyTransacted(channel); if (channelLocallyTransacted) { channel.basicAck(deliveryTag, false); } else if (channelTransacted) { // Not locally transacted but it is transacted so it could be synchronized with an external transaction ConnectionFactoryUtils.registerDeliveryTag(RabbitTemplate.this.getConnectionFactory(), channel, deliveryTag); } Message receiveMessage = RabbitTemplate.this.buildMessageFromResponse(response); Object receive = receiveMessage; if (!(ReceiveAndReplyMessageCallback.class.isAssignableFrom(callback.getClass()))) { receive = RabbitTemplate.this.getRequiredMessageConverter().fromMessage(receiveMessage); } S reply; try { reply = callback.handle((R) receive); } catch (ClassCastException e) { StackTraceElement[] trace = e.getStackTrace(); if (trace[0].getMethodName().equals("handle") && trace[1].getFileName().equals("RabbitTemplate.java")) { throw new IllegalArgumentException("ReceiveAndReplyCallback '" + callback + "' can't handle received object '" + receive + "'", e); } else { throw e; } } if (reply != null) { Address replyTo = replyToAddressCallback.getReplyToAddress(receiveMessage, reply); Message replyMessage = RabbitTemplate.this.convertMessageIfNecessary(reply); MessageProperties receiveMessageProperties = receiveMessage.getMessageProperties(); MessageProperties replyMessageProperties = replyMessage.getMessageProperties(); Object correlation = RabbitTemplate.this.correlationKey == null ? receiveMessageProperties.getCorrelationId() : receiveMessageProperties.getHeaders().get(RabbitTemplate.this.correlationKey); if (RabbitTemplate.this.correlationKey == null || correlation == null) { // using standard correlationId property if (correlation == null) { String messageId = receiveMessageProperties.getMessageId(); if (messageId != null) { correlation = messageId.getBytes(RabbitTemplate.this.encoding); } } replyMessageProperties.setCorrelationId((byte[]) correlation); } else { replyMessageProperties.setHeader(RabbitTemplate.this.correlationKey, correlation); } // 'doSend()' takes care about 'channel.txCommit()'. RabbitTemplate.this.doSend(channel, replyTo.getExchangeName(), replyTo.getRoutingKey(), replyMessage, null); } else if (channelLocallyTransacted) { channel.txCommit(); } return true; } return false; } }); }
From source file:org.springframework.amqp.rabbit.core.RabbitTemplateIntegrationTests.java
License:Apache License
@Test public void testSendAndReceiveInCallback() throws Exception { template.convertAndSend(ROUTE, "message"); final MessagePropertiesConverter messagePropertiesConverter = new DefaultMessagePropertiesConverter(); String result = template.execute(new ChannelCallback<String>() { @Override/* ww w.j av a 2 s .c om*/ public String doInRabbit(Channel channel) throws Exception { // We need noAck=false here for the message to be expicitly // acked GetResponse response = channel.basicGet(ROUTE, false); MessageProperties messageProps = messagePropertiesConverter.toMessageProperties(response.getProps(), response.getEnvelope(), "UTF-8"); // Explicit ack channel.basicAck(response.getEnvelope().getDeliveryTag(), false); return (String) new SimpleMessageConverter() .fromMessage(new Message(response.getBody(), messageProps)); } }); assertEquals("message", result); result = (String) template.receiveAndConvert(ROUTE); assertEquals(null, result); }
From source file:org.voltdb.bulkloader.RMQCSVReceive.java
License:Open Source License
public static void receiveMessages(RMQOptions rmqOpts, TestOptions testOpts, String[] args) throws IOException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(rmqOpts.host);//from ww w . j av a2 s . co m Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); if (rmqOpts.exchange != null) { if (rmqOpts.extype != null) { channel.exchangeDeclare(rmqOpts.exchange, rmqOpts.extype); } for (String bindingKey : rmqOpts.bindings) { channel.queueBind(rmqOpts.queue, rmqOpts.exchange, bindingKey); } } try { channel.queueDeclare(rmqOpts.queue, rmqOpts.persistent, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); channel.basicQos(1); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(rmqOpts.queue, false, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); // Sleep 1 second for every trailing '.'. int dotCount = 0; for (int i = message.length() - 1; i >= 0; --i) { if (message.charAt(i) == '.') { dotCount++; } else { break; } } if (dotCount > 0) { message = message.substring(0, message.length() - dotCount); } System.out.printf(" [x] Received '%s'\n", message); Thread.sleep(dotCount * 1000); } } catch (ShutdownSignalException | ConsumerCancelledException | InterruptedException e) { e.printStackTrace(); } finally { channel.close(); connection.close(); } }