Example usage for com.rabbitmq.client Channel basicAck

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

Introduction

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

Prototype

void basicAck(long deliveryTag, boolean multiple) throws IOException;

Source Link

Document

Acknowledge one or several received messages.

Usage

From source file:com.mycompany.javateste.queues.worktasks.Worker.java

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    final Connection connection = factory.newConnection();
    final Channel channel = connection.createChannel();

    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    channel.basicQos(1);/*from w  w w  .java2  s  .c  om*/

    final Consumer consumer = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");

            System.out.println(" [x] Received '" + message + "'");
            try {
                doWork(message);
            } finally {
                System.out.println(" [x] Done");
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        }
    };
    channel.basicConsume(TASK_QUEUE_NAME, false, consumer);
}

From source file:com.nesscomputing.amqp.AbstractConsumer.java

License:Apache License

@Override
protected boolean process() throws IOException, InterruptedException {
    channelConnect();// w  w w  .j  av  a2  s . c  o m
    final QueueingConsumer consumer = consumerHolder.get();

    if (consumer == null) {
        // When the channel is not connected, this can happen. Simulate a tick.
        LOG.warn("Channel not connected!");
        Thread.sleep(tickTimeout);
        return true;
    } else {
        final QueueingConsumer.Delivery delivery = consumer.nextDelivery(tickTimeout);
        if (delivery != null) {
            try {
                return consumerCallback.withDelivery(delivery);
            } finally {
                final Channel channel = getChannel();
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        } else {
            LOG.trace("Tick...");
        }
        return true;
    }
}

From source file:com.netcore.hsmart.dlrconsumers.DlrConsumer1000.java

/**
 * @param args the command line arguments
 * @throws java.lang.Exception/*w w w . ja  v a 2s . c o m*/
 */
public static void main(String[] args) throws Exception {

    /**
     * Set properties at runtime
     */
    System.setProperty("dlrconsumer_logfile", "557_dlr_consumer.log");
    AppConstants.loadAppConfig();

    final String queueName = AppConstants.getDlrReceiverQueuePrefix() + GATEWAY_ID;
    final String exchangeName = AppConstants.getDlrReceiverExchangeName();
    final String routingKey = GATEWAY_ID;

    Logger logger = LoggerFactory.getLogger(DlrConsumer1000.class);

    try {

        Connection connection = AppConstants.getRabbitMqObject().newConnection();

        connection.addShutdownListener(new ShutdownListener() {
            @Override
            public void shutdownCompleted(ShutdownSignalException cause) {
                //throw new UnsupportedOperationException("Not supported yet.");
                if (cause.isHardError()) {
                    Connection conn;
                    conn = (Connection) cause.getReference();
                    if (!cause.isInitiatedByApplication()) {
                        Method reason = cause.getReason();
                        logger.info("REASON:" + reason.toString());
                    }

                } else {
                    Channel ch = (Channel) cause.getReference();
                    logger.info("NO HARDSHUTDOWN");
                }
            }
        });

        Channel channel = connection.createChannel();

        channel.exchangeDeclare(exchangeName, "direct");
        channel.queueDeclare(queueName, true, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);
        channel.basicQos(1000);
        //channel.addShutdownListener(listener);
        logger.info(" [*] Waiting for messages from gateway " + GATEWAY_ID + ". To exit press CTRL+C");

        Consumer consumer;

        consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {

                Map<String, String> dataToPost = new HashMap<>();
                String payload = new String(body, "UTF-8");

                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|START+++++++++++++++");
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|PAYLOAD:" + payload);

                String payloadParts[] = payload.split(AppConstants.getPayloadGroupSeparator());

                for (String payloadPart : payloadParts) {
                    String s[] = payloadPart.split(AppConstants.getPayloadKVSeparator());

                    //check if any parameter is empty
                    if (s.length == 2) {
                        dataToPost.put(s[0], s[1]);
                    } else {
                        logger.info("REF_ID:" + dataToPost.get("ref_id") + "|EMPTY_PARAM:" + s[0]);
                        dataToPost.put(s[0], null);
                    }
                }

                long deliveryTag = envelope.getDeliveryTag();

                if (invokeApiCall(dataToPost)) {
                    channel.basicAck(deliveryTag, false);

                } else {
                    channel.basicNack(deliveryTag, false, true);
                }

                /**
                 * release memory
                 */
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|END-----------------");
                dataToPost.clear();
                payloadParts = null;

            }
        };

        String cTag = channel.basicConsume(queueName, false, consumer);
        logger.info("CONSUMER TAG : " + cTag);

    } catch (IOException | TimeoutException e) {
        logger.error("RMQ_ERROR:" + e.getMessage());
    }
}

From source file:com.netcore.hsmart.smsconsumers.SmsConsumer1000.java

/**
 * @param args the command line arguments
 * @throws java.lang.Exception/*from  w w  w  .  j  av a 2  s .co  m*/
 */
public static void main(String[] args) throws Exception {

    /**
     * Set properties at runtime
     */
    System.setProperty("smsconsumer_logfile", GATEWAY_ID + "_sms_consumer.log");
    AppConstants.loadAppConfig();

    final String queueName = AppConstants.getSmsReceiverQueuePrefix() + GATEWAY_ID;
    final String exchangeName = AppConstants.getSmsReceiverExchangeName();
    final String routingKey = GATEWAY_ID;

    Logger logger = LoggerFactory.getLogger(SmsConsumer1000.class);

    try {

        Connection connection = AppConstants.getRabbitMqObject().newConnection();

        connection.addShutdownListener(new ShutdownListener() {
            @Override
            public void shutdownCompleted(ShutdownSignalException cause) {
                //throw new UnsupportedOperationException("Not supported yet.");
                if (cause.isHardError()) {
                    Connection conn;
                    conn = (Connection) cause.getReference();
                    if (!cause.isInitiatedByApplication()) {
                        Method reason = cause.getReason();
                        logger.info("REASON:" + reason.toString());
                    }

                } else {
                    Channel ch = (Channel) cause.getReference();
                    logger.info("NO HARDSHUTDOWN");
                }
            }
        });

        Channel channel = connection.createChannel();

        channel.exchangeDeclare(exchangeName, "direct");
        channel.queueDeclare(queueName, true, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);
        channel.basicQos(1000);
        //channel.addShutdownListener(listener);
        logger.info(" [*] Waiting for messages from gateway " + GATEWAY_ID + ". To exit press CTRL+C");

        Consumer consumer;

        consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {

                Map<String, String> dataToPost = new HashMap<>();
                String payload = new String(body, "UTF-8");

                String payloadParts[] = payload.split(AppConstants.getPayloadGroupSeparator());

                for (String payloadPart : payloadParts) {
                    String s[] = payloadPart.split(AppConstants.getPayloadKVSeparator());
                    dataToPost.put(s[0], s[1]);
                }
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|START+++++++++++++++");
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|PAYLOAD:" + payload);

                long deliveryTag = envelope.getDeliveryTag();

                if (invokeApiCall(dataToPost)) {
                    if (saveRequestData()) {

                        channel.basicAck(deliveryTag, false);
                    } else {
                        channel.basicNack(deliveryTag, false, true);
                    }

                } else {
                    channel.basicNack(deliveryTag, false, true);
                }

                /**
                 * release memory
                 */
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|END-----------------");
                API_CALL_STATS.clear();
                dataToPost.clear();
                payloadParts = null;

            }
        };

        String cTag = channel.basicConsume(queueName, false, consumer);
        logger.info("CONSUMER TAG : " + cTag);

    } catch (IOException | TimeoutException e) {
        logger.error("RMQ_ERROR:" + e.getMessage());
    }
}

From source file:com.trivago.mail.pigeon.daemon.Daemon.java

License:Apache License

/**
 * Main Daemon method containing the event loop.
 *
 * @param args command line args/*from   w w w .  j  a va 2s . co  m*/
 * @throws java.io.IOException
 */
public static void main(String[] args) throws IOException {

    Connection conn = null;
    Channel channel = null;

    try {
        conn = ConnectionPool.getConnection();
        channel = conn.createChannel();

        boolean autoAck = false;
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(channelName, autoAck, consumer);
        MailFacade mailFacade = new MailFacade();

        while (true) {
            QueueingConsumer.Delivery delivery;
            try {
                delivery = consumer.nextDelivery();
            } catch (InterruptedException ie) {
                continue;
            }

            String jsonContent = new String(delivery.getBody());
            MailTransport mailTransport = JSONParser.defaultJSONParser().parse(MailTransport.class,
                    jsonContent);
            mailFacade.sendMail(mailTransport);
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }

    } finally {
        if (channel != null) {
            channel.close();
        }
        if (conn != null) {
            conn.close();
        }
    }
}

From source file:com.ushahidi.swiftriver.core.dropqueue.MetadataResponseHandler.java

License:Open Source License

/**
 * Receive drop that has completed metadata extraction.
 * /*from www  .  j  a  va  2s .  co  m*/
 * Updates the locally cached drop with received metadata. 
 * Drops that have completed both media and sematic extraction
 * get added to the publishQueue for posting to the API.
 * 
 * @param message
 * @param channel
 * @throws Exception
 */
public void onMessage(Message message, Channel channel) throws Exception {
    String correlationId = new String(message.getMessageProperties().getCorrelationId());
    RawDrop updatedDrop = objectMapper.readValue(new String(message.getBody()), RawDrop.class);

    logger.info("Metadata Response received from '{}' with correlation_id '{}'", updatedDrop.getSource(),
            correlationId);

    synchronized (dropsMap) {
        RawDrop cachedDrop = dropsMap.get(correlationId);

        // Verify that the drop exists in the in-memory cache
        if (cachedDrop == null) {
            logger.error("Drop with correlation id '{}' not found in cache", correlationId);

            // Acknowledge receipt
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            return;
        }

        if (updatedDrop.getSource().equals("mediaextractor")) {
            cachedDrop.setMediaComplete(true);
            cachedDrop.setMedia(updatedDrop.getMedia());
            cachedDrop.setLinks(updatedDrop.getLinks());
        } else if (updatedDrop.getSource().equals("semantics")) {
            cachedDrop.setSemanticsComplete(true);
            cachedDrop.setTags(updatedDrop.getTags());
            cachedDrop.setPlaces(updatedDrop.getPlaces());
        } else if (updatedDrop.getSource().equals("rules")) {
            cachedDrop.setBucketIds(updatedDrop.getBucketIds());
            cachedDrop.setRiverIds(updatedDrop.getRiverIds());
            cachedDrop.setMarkAsRead(updatedDrop.getMarkAsRead());
            cachedDrop.setRulesComplete(true);
        }

        // When semantics and metadata extraction are complete,
        // submit for rules processing
        if (cachedDrop.isSemanticsComplete() && cachedDrop.isMediaComplete()) {
            logger.info("Sending drop with correlation id '{}' for rules processing", correlationId);
            dropFilterQueue.put(correlationId);
        }

        if (cachedDrop.isSemanticsComplete() && cachedDrop.isMediaComplete() && cachedDrop.isRulesComplete()) {

            // Queue the drop for posting via the API
            if (cachedDrop.getRiverIds() != null && !cachedDrop.getRiverIds().isEmpty()) {
                publishQueue.put(cachedDrop);
            } else {
                logger.info("No destination rivers for drop with correlation id '{}'", correlationId);
            }

            dropsMap.remove(correlationId);

            // Confirm the drop has completed processing
            DeliveryFrame deliveryFrame = deliveryFramesMap.remove(correlationId);
            Channel confirmChannel = deliveryFrame.getChannel();
            confirmChannel.basicAck(deliveryFrame.getDeliveryTag(), false);

            // Log
            logger.info("Drop with correlation id '{}' has completed metadata extraction", correlationId);
        }
    }
}

From source file:com.ushahidi.swiftriver.core.rules.DropFilterQueueConsumer.java

License:Open Source License

public synchronized void onMessage(Message message, Channel channel)
        throws JsonGenerationException, JsonMappingException, IOException {

    // Serialize the message into a Drop POJO
    RawDrop drop = objectMapper.readValue(new String(message.getBody()), RawDrop.class);

    ConcurrentMap<Long, Map<Long, Rule>> rulesMap = rulesRegistry.getRulesMap();

    // Send the drop for rules processing
    rulesExecutor.applyRules(drop, rulesMap);

    // Set the source to "rules"
    drop.setSource("rules");

    // Get he correlation id and callback queue name
    final String correlationId = new String(message.getMessageProperties().getCorrelationId());
    String routingKey = message.getMessageProperties().getReplyTo();
    long deliveryTag = message.getMessageProperties().getDeliveryTag();

    // Place drop on the publishing queue
    amqpTemplate.convertAndSend(routingKey, drop, new MessagePostProcessor() {
        public Message postProcessMessage(Message message) throws AmqpException {
            try {
                message.getMessageProperties().setCorrelationId(correlationId.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                logger.error("An error occurred while setting the correlation ID {}", correlationId, e);
            }/*from w  w w  . j  a  v a2s .com*/

            return message;
        }

    });

    // Only acknowledge the current message
    channel.basicAck(deliveryTag, false);

    logger.debug("Drop with correlation id {} has completed rules processing", correlationId);
}

From source file:com.viadeo.kasper.core.component.event.eventbus.EventMessageHandler.java

License:Open Source License

@Override
public void onMessage(Message message, Channel channel) throws Exception {
    final long deliveryTag = message.getMessageProperties().getDeliveryTag();
    final EventMessage eventMessage;

    try {//from  ww w  .j  a v  a 2 s .com
        eventMessage = (EventMessage) converter.fromMessage(message);
    } catch (Throwable e) {
        messageRecoverer.recover(message, new MessageHandlerException(eventListener.getClass(), e));
        channel.basicNack(deliveryTag, false, false);
        return;
    }

    metricRegistry.counter(HANDLE_MESSAGE_COUNT_METRIC).inc();
    metricRegistry.histogram(HANDLE_MESSAGE_TIME_METRIC).update(timeTaken(eventMessage));

    MDC.setContextMap(Maps.transformEntries(eventMessage.getMetaData(),
            new Maps.EntryTransformer<String, Object, String>() {
                @Override
                public String transformEntry(String key, Object value) {
                    return String.valueOf(value);
                }
            }));

    EventResponse response = null;

    try {
        response = eventListener
                .handle(new com.viadeo.kasper.core.component.event.listener.EventMessage(eventMessage));
    } catch (Exception e) {
        logger.error("Can't process event", e);
        response = EventResponse.failure(new KasperReason(CoreReasonCode.INTERNAL_COMPONENT_ERROR, e));
    }

    final KasperReason reason = response.getReason();

    switch (response.getStatus()) {

    case SUCCESS:
    case OK:
        logger.debug("Successfully handled the event message ({}) by '{}'", eventMessage.getIdentifier(),
                eventListener.getName());
        channel.basicAck(deliveryTag, false);
        break;

    case ERROR:
        if (reason.getException().isPresent()) {
            logger.warn("Failed to handle the event message ({}) by '{}' : {}", eventMessage.getIdentifier(),
                    eventListener.getName(), reason.getMessages(), reason.getException().get());
        } else {
            logger.warn("Failed to handle the event message ({}) by '{}' : {}", eventMessage.getIdentifier(),
                    eventListener.getName(), reason.getMessages());
        }
        channel.basicAck(deliveryTag, false);
        break;

    case FAILURE:
        metricRegistry.counter(HANDLE_MESSAGE_ERROR_METRIC).inc();

        final Integer nbAttempt = getIncrementedNbAttempt(message);
        final DateTime time = new DateTime(message.getMessageProperties().getTimestamp());

        LOGGER.debug("Failed to attempt to handle the event message ({}) : {} time(s) by '{}'",
                eventMessage.getIdentifier(), nbAttempt, eventListener.getName());

        if (response.isTemporary()) {
            if (nbAttempt >= maxAttempts) {
                if (DateTime.now().minusHours(requeueThresholdInHours).isBefore(time)) {
                    LOGGER.info("Requeue the event message ({}) in the related queue of '{}'",
                            eventMessage.getIdentifier(), eventListener.getClass().getSimpleName());
                    channel.basicNack(deliveryTag, false, true);
                    return;
                } else {
                    messageRecoverer.recover(message, new MessageHandlerException(eventListener.getClass(),
                            reason.getException().or(new RuntimeException("Failed to handle event message"))));
                    channel.basicNack(deliveryTag, false, false);
                    return;
                }
            }
        } else if (nbAttempt >= maxAttempts) {
            messageRecoverer.recover(message, new MessageHandlerException(eventListener.getClass(),
                    reason.getException().or(new RuntimeException("Failed to handle event message"))));
            channel.basicNack(deliveryTag, false, false);
            break;
        }

        throw new MessageHandlerException(eventListener.getClass(),
                reason.getException().or(new KasperEventException(response.getReason().toString())));

    default:
        messageRecoverer.recover(message,
                new MessageHandlerException(eventListener.getClass(), reason.getException().or(
                        new RuntimeException(String.format("Status not managed '%s'", response.getStatus())))));
        channel.basicNack(deliveryTag, false, false);
        break;
    }
}

From source file:com.vmware.bdd.utils.RabbitMQConsumer.java

License:Open Source License

/**
 * Receive and process each message until the listener indicating. A new
 * queue will be created when start and will be deleted when stopping
 * receiving message.//from  w  ww.  j  ava2s  . c o  m
 * 
 * FIXME Is it a best practice to create one queue for one task? Or we should
 * create one thread to handle all messages?
 * 
 * @param listener
 *           message processor callback
 * @throws IOException
 */
public void processMessage(MessageListener listener) throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    if (username != null && !username.equals("")) {
        factory.setUsername(username);
        factory.setPassword(password);
    }
    factory.setVirtualHost("/");
    factory.setHost(host);
    factory.setPort(port);

    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();

    /**
     * make exchange and queue non-durable
     */
    channel.exchangeDeclare(exchangeName, "direct", true);
    if (!getQueue) {
        channel.queueDeclare(queueName, false, true, true, null);
    } else {
        queueName = channel.queueDeclare().getQueue();
    }
    channel.queueBind(queueName, exchangeName, routingKey);

    boolean noAck = false;
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, noAck, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery;
        try {
            delivery = consumer.nextDelivery(mqRecvTimeoutMs);
        } catch (InterruptedException e) {
            logger.warn("message consumer interrupted", e);
            continue;
        }

        if (delivery == null) {
            logger.debug("timeout, no message received");
            if (stopping && new Date().after(mqExpireTime)) {
                logger.error("stop receiving messages without normal termination");
                break;
            }
            continue;
        }

        String message = new String(delivery.getBody());
        if (graceStopping) {
            extendExpirationTime();
        }

        logger.info("message received: " + message);
        try {
            if (!listener.onMessage(message)) {
                logger.info("stop receiving messages normally");
                break;
            }
        } catch (Throwable t) {
            logger.error("calling message listener failed", t);
            // discard and continue in non-debug mode
            AuAssert.unreachable();
        }
        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }

    try {
        channel.queueDelete(queueName);
    } catch (AlreadyClosedException e) {
        logger.error("failed to delete queue: " + queueName, e);
    }

    try {
        channel.close();
    } catch (AlreadyClosedException e) {
        logger.error("failed to close channel, queue: " + queueName, e);
    }

    try {
        conn.close();
    } catch (AlreadyClosedException e) {
        logger.error("failed to close connection, queue: " + queueName, e);
    }
}

From source file:com.wss.qvh.log.ConsumerThread.java

public void consumer() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(Constant.RABBITMQ_USERNAME);
    factory.setPassword(Constant.RABBITMQ_PASSWORD);
    factory.setVirtualHost(Constant.RABBITMQ_VIRTUAL_HOST);
    factory.setRequestedChannelMax(Constant.NUM_PRODUCER);
    factory.setHost(Constant.RABBITMQ_HOST);

    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(Constant.QUEUE_NAME, Constant.QUEUE_DURABLE, false, false, null);
    channel.basicQos(Constant.QUEUE_PREFETCH);
    QueueingConsumer consumer = new QueueingConsumer(channel);
    boolean autoAck = false;
    channel.basicConsume(Constant.QUEUE_NAME, autoAck, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery;
        try {/*from  w w  w .jav a  2  s  .com*/
            delivery = consumer.nextDelivery();
        } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException ex) {
            logger.warn(ex.getMessage(), ex);
            try {
                Thread.sleep(100L);
            } catch (InterruptedException ex1) {
                logger.warn(ex1.getMessage(), ex1);
            }
            continue;
        }

        String message;
        try {
            message = getMessenge(delivery);
        } catch (InterruptedException ex) {
            logger.warn(ex.getMessage(), ex);
            try {
                Thread.sleep(100L);
            } catch (InterruptedException ex1) {
                logger.warn(ex1.getMessage(), ex1);
            }
            continue;
        }
        if (message == null || message.isEmpty()) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
                logger.warn(ex.getMessage(), ex);
            }
        } else {
            LogObject lo = new LogObject();
            try {
                lo.parseJson(message);
                store(lo);
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            } catch (Exception ex) {
                logger.debug(message, ex);
            }
        }
    }
}