Example usage for com.rabbitmq.client Channel basicConsume

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

Introduction

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

Prototype

String basicConsume(String queue, boolean autoAck, String consumerTag, Consumer callback) throws IOException;

Source Link

Document

Start a non-nolocal, non-exclusive consumer.

Usage

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

License:Apache License

public void registerMessageHandler(MessageHandler messageHandler, boolean autoAck) {
    if (isRegistered.compareAndSet(false, true)) {
        try {/*from   w  w  w.j  av a 2s . c om*/
            if (messageHandler instanceof AbstractRabbitMQMessageHandler) {
                String consumerTag = FlowContextFactory.getFlowContext() != null
                        ? FlowContextFactory.getFlowContext().getUniqueId()
                        : "N/A";
                Channel channel = RabbitMQMessagingFactory.getChannel();
                this.channelNumber = channel.getChannelNumber();
                ((AbstractRabbitMQMessageHandler) messageHandler).setChannelNumber(channelNumber);
                this.consumerTag = channel.basicConsume(queueName, autoAck, consumerTag,
                        (Consumer) messageHandler);
            } else {
                throw new IllegalArgumentException(
                        "Using RabbitMQ consumerThreadLocal you must provide a valid RabbitMQ massage handler");
            }

        } catch (IOException e) {
            //            LOGGER.error("can't register a MessageHandler: {}", e);
            throw new QueueException("can't register a MessageHandler: " + e, e);
        }
    }
}

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

License:Apache License

public void registerMessageHandler(MessageHandler messageHandler, boolean autoAck) {
    if (isRegistered.compareAndSet(false, true)) {
        try {/*from   w  ww . ja  v a 2  s  .c o  m*/
            if (messageHandler instanceof AbstractRabbitMQMessageHandler) {
                String consumerTag = FlowContextFactory.getFlowContext() != null
                        ? FlowContextFactory.getFlowContext().getUniqueId()
                        : "N/A";
                Channel channel = consumer.getChannel();
                ((AbstractRabbitMQMessageHandler) messageHandler).setChannelNumber(channel.getChannelNumber());
                this.consumerTag = channel.basicConsume(queueName, autoAck, consumerTag,
                        (Consumer) messageHandler);
            } else {
                throw new IllegalArgumentException(
                        "Using RabbitMQ consumerThreadLocal you must provide a valid RabbitMQ massage handler");
            }

        } catch (IOException e) {
            //            LOGGER.error("can't register a MessageHandler: {}", e);
            throw new QueueException("can't register a MessageHandler: " + e, e);
        }
    }
}

From source file:com.ericsson.research.IoTFrameworkEndpoint.java

License:Open Source License

public void subscribe(String hostName, String StreamId, final DataPointCallback dataPointCallback)
        throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(hostName); // listening on port 5672

    Connection connection = factory.newConnection();

    final Channel channel = connection.createChannel();
    final String EXCHANGE_NAME = "streams." + StreamId;

    channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, EXCHANGE_NAME, "");

    dataPointCallback.setConnection(connection);

    boolean autoAck = true;
    channel.basicConsume(queueName, autoAck, "myConsumerTag", new DefaultConsumer(channel) {
        @Override//from  w  w w  .  j  a va 2 s.c  om
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            DataPointNotification notification = gson.fromJson(new String(body), DataPointNotification.class);
            dataPointCallback.handleNotification(notification);
        }
    });
}

From source file:io.qdb.server.input.RabbitMQInputHandler.java

License:Apache License

@Override
public void start(final Sink sink) throws Exception {
    this.sink = sink;
    final Channel c = ensureChannel();
    c.basicConsume(queue, autoAck, "qdb:" + inputPath, new DefaultConsumer(c) {
        @Override//  w  ww. j  a v  a 2  s  .  com
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            boolean ok = false;
            try {
                sink.append(envelope.getRoutingKey(), body);
                if (!autoAck)
                    c.basicAck(envelope.getDeliveryTag(), false);
                ok = true;
            } catch (Exception e) {
                sink.error(e);
            } finally {
                if (!ok) {
                    try {
                        // todo should probably sit on the message for a bit before nacking to prevent storm
                        c.basicNack(envelope.getDeliveryTag(), false, true);
                    } catch (IOException e) {
                        log.debug("Error nacking message: " + e, e);
                    }
                }
            }
        }
    });
}

From source file:net.lshift.accent.AccentConsumer.java

License:Apache License

@Override
public void channelCreated(Channel c) throws IOException {
    c.basicConsume(queue, AUTO_ACK, consumerTag, delegate);
    hasUnderlyingConsume = true;//from   w ww  .  ja v a 2  s .c o m
}

From source file:org.apache.cloudstack.mom.rabbitmq.RabbitMQEventBus.java

License:Apache License

/** Call to subscribe to interested set of events
 *
 * @param topic defines category and type of the events being subscribed to
 * @param subscriber subscriber that intends to receive event notification
 * @return UUID that represents the subscription with event bus
 * @throws EventBusException//w  w  w .  jav a  2s  .  c  o  m
 */
@Override
public UUID subscribe(EventTopic topic, EventSubscriber subscriber) throws EventBusException {

    if (subscriber == null || topic == null) {
        throw new EventBusException("Invalid EventSubscriber/EventTopic object passed.");
    }

    // create a UUID, that will be used for managing subscriptions and also used as queue name
    // for on the queue used for the subscriber on the AMQP broker
    UUID queueId = UUID.randomUUID();
    String queueName = queueId.toString();

    try {
        String bindingKey = createBindingKey(topic);

        // store the subscriber details before creating channel
        _subscribers.put(queueName, new Ternary(bindingKey, null, subscriber));

        // create a channel dedicated for this subscription
        Connection connection = getConnection();
        Channel channel = createChannel(connection);

        // create a queue and bind it to the exchange with binding key formed from event topic
        createExchange(channel, amqpExchangeName);
        channel.queueDeclare(queueName, false, false, false, null);
        channel.queueBind(queueName, amqpExchangeName, bindingKey);

        // register a callback handler to receive the events that a subscriber subscribed to
        channel.basicConsume(queueName, _autoAck, queueName, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String queueName, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {
                Ternary<String, Channel, EventSubscriber> queueDetails = _subscribers.get(queueName);
                if (queueDetails != null) {
                    EventSubscriber subscriber = queueDetails.third();
                    String routingKey = envelope.getRoutingKey();
                    String eventSource = getEventSourceFromRoutingKey(routingKey);
                    String eventCategory = getEventCategoryFromRoutingKey(routingKey);
                    String eventType = getEventTypeFromRoutingKey(routingKey);
                    String resourceType = getResourceTypeFromRoutingKey(routingKey);
                    String resourceUUID = getResourceUUIDFromRoutingKey(routingKey);
                    Event event = new Event(eventSource, eventCategory, eventType, resourceType, resourceUUID);
                    event.setDescription(new String(body));

                    // deliver the event to call back object provided by subscriber
                    subscriber.onEvent(event);
                }
            }
        });

        // update the channel details for the subscription
        Ternary<String, Channel, EventSubscriber> queueDetails = _subscribers.get(queueName);
        queueDetails.second(channel);
        _subscribers.put(queueName, queueDetails);

    } catch (AlreadyClosedException closedException) {
        s_logger.warn("Connection to AMQP service is lost. Subscription:" + queueName
                + " will be active after reconnection");
    } catch (ConnectException connectException) {
        s_logger.warn("Connection to AMQP service is lost. Subscription:" + queueName
                + " will be active after reconnection");
    } catch (Exception e) {
        throw new EventBusException("Failed to subscribe to event due to " + e.getMessage());
    }

    return queueId;
}

From source file:org.pascani.dsl.lib.infrastructure.rabbitmq.RabbitMQConsumer.java

License:Open Source License

@Override
protected void startConsuming() {
    Channel channel = this.endPoint.channel();
    try {/*from w w w .  ja  v  a2  s .co m*/
        // start consuming (non auto-acknowledged) messages
        channel.basicConsume(this.queueName, false, this.consumerTag, this);
    } catch (IOException e) {
        logger.error("Error consuming message from RabbitMQ consumer", e);
    }
}

From source file:reactor.rabbitmq.ConnectionRecoveryTests.java

License:Open Source License

@Test
void consumeAutoAckRetryOnAck() 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);

    CountDownLatch consumerRegisteredLatch = new CountDownLatch(1);
    AtomicReference<DeliverCallback> deliverCallbackAtomicReference = new AtomicReference<>();

    when(mockChannel.basicConsume(anyString(), anyBoolean(), any(DeliverCallback.class),
            any(CancelCallback.class))).thenAnswer(answer -> {
                deliverCallbackAtomicReference.set(answer.getArgument(2));
                consumerRegisteredLatch.countDown();
                return "ctag";
            });// w  w  w. java2 s  .co m

    AtomicLong ackCount = new AtomicLong(0);
    AtomicLong errorAck = new AtomicLong(0);
    doAnswer(answer -> {
        ackCount.incrementAndGet();
        if (ackCount.get() == 3 || ackCount.get() == 4) {
            errorAck.incrementAndGet();
            throw new AlreadyClosedException(new ShutdownSignalException(true, false, null, null));
        }
        return null;
    }).when(mockChannel).basicAck(anyLong(), anyBoolean());

    receiver = RabbitFlux.createReceiver(new ReceiverOptions().connectionSupplier(cf -> mockConnection));

    AtomicInteger ackedMessages = new AtomicInteger(0);
    receiver.consumeAutoAck("whatever",
            new ConsumeOptions().exceptionHandler(new ExceptionHandlers.RetryAcknowledgmentExceptionHandler(
                    ofSeconds(5), ofMillis(100), ExceptionHandlers.CONNECTION_RECOVERY_PREDICATE)))
            .subscribe(msg -> {
                ackedMessages.incrementAndGet();
            });

    assertTrue(consumerRegisteredLatch.await(1, TimeUnit.SECONDS),
            "Consumer should have been registered by now");

    int nbMessages = 10;
    IntStream.range(0, nbMessages).forEach(i -> {
        try {
            deliverCallbackAtomicReference.get().handle("",
                    new Delivery(new Envelope(i, true, null, null), null, null));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });

    assertEquals(nbMessages, ackedMessages.get(), "All messages should have been ack-ed, as ack is retried");
    assertEquals(nbMessages + errorAck.get(), ackCount.get(),
            "There should have been nbMessages+ackInError calls to basicAck as acknowledgments are retried");
}

From source file:reactor.rabbitmq.ConnectionRecoveryTests.java

License:Open Source License

@Test
void consumeManualAckRetryOnAck() 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);

    CountDownLatch consumerRegisteredLatch = new CountDownLatch(1);
    AtomicReference<DeliverCallback> deliverCallbackAtomicReference = new AtomicReference<>();

    when(mockChannel.basicConsume(anyString(), anyBoolean(), any(DeliverCallback.class),
            any(CancelCallback.class))).thenAnswer(answer -> {
                deliverCallbackAtomicReference.set(answer.getArgument(2));
                consumerRegisteredLatch.countDown();
                return "ctag";
            });/*from  w  w  w  .jav  a 2 s .  co  m*/

    AtomicLong ackCount = new AtomicLong(0);
    doAnswer(answer -> {
        ackCount.incrementAndGet();
        if (ackCount.get() == 3 || ackCount.get() == 4) {
            throw new AlreadyClosedException(new ShutdownSignalException(true, false, null, null));
        }
        return null;
    }).when(mockChannel).basicAck(anyLong(), anyBoolean());

    receiver = RabbitFlux.createReceiver(new ReceiverOptions().connectionSupplier(cf -> mockConnection));

    AtomicInteger ackedMessages = new AtomicInteger(0);
    BiConsumer<Receiver.AcknowledgmentContext, Exception> exceptionHandler = new ExceptionHandlers.RetryAcknowledgmentExceptionHandler(
            ofSeconds(5), ofMillis(100), ExceptionHandlers.CONNECTION_RECOVERY_PREDICATE);
    receiver.consumeManualAck("whatever", new ConsumeOptions().exceptionHandler(exceptionHandler))
            .subscribe(msg -> {
                // do business stuff
                // ...
                // trying to ack
                msg.ack();
                ackedMessages.incrementAndGet();
            });

    assertTrue(consumerRegisteredLatch.await(1, TimeUnit.SECONDS),
            "Consumer should have been registered by now");

    int nbMessages = 10;
    IntStream.range(0, nbMessages).forEach(i -> {
        try {
            deliverCallbackAtomicReference.get().handle("",
                    new Delivery(new Envelope(i, true, null, null), null, null));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });

    assertEquals(nbMessages, ackedMessages.get(), "All messages should have been ack-ed, as ack is retried");
}

From source file:reactor.rabbitmq.ConnectionRecoveryTests.java

License:Open Source License

@Test
public void sendWithPublishConfirmsAllMessagesShouldBeSentConfirmedAndConsumed() throws Exception {
    int nbMessages = 10;
    CountDownLatch consumedLatch = new CountDownLatch(nbMessages);
    CountDownLatch confirmedLatch = new CountDownLatch(nbMessages);
    AtomicInteger counter = new AtomicInteger();
    Channel channel = connection.createChannel();
    channel.basicConsume(queue, true, (consumerTag, delivery) -> {
        counter.incrementAndGet();/*w  w w.  j a  va 2 s.  co  m*/
        consumedLatch.countDown();
    }, consumerTag -> {
    });

    Flux<OutboundMessage> msgFlux = Flux.range(0, nbMessages)
            .map(i -> new OutboundMessage("", queue, "".getBytes())).delayElements(ofMillis(300));

    sender = createSender(new SenderOptions().connectionMono(connectionMono));
    sender.sendWithPublishConfirms(msgFlux,
            new SendOptions().exceptionHandler(new ExceptionHandlers.RetrySendingExceptionHandler(ofSeconds(5),
                    ofMillis(100), ExceptionHandlers.CONNECTION_RECOVERY_PREDICATE)))
            .subscribe(outboundMessageResult -> {
                if (outboundMessageResult.isAck() && outboundMessageResult.getOutboundMessage() != null) {
                    confirmedLatch.countDown();
                }
            });

    closeAndWaitForRecovery((RecoverableConnection) connectionMono.block());

    assertTrue(consumedLatch.await(10, TimeUnit.SECONDS));
    assertTrue(confirmedLatch.await(10, TimeUnit.SECONDS));
    assertEquals(nbMessages, counter.get());
}