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:play.modules.rabbitmq.consumer.RabbitMQConsumer.java

License:Apache License

/**
 * Go get her son./*ww  w .j  av  a2 s .c om*/
 */
private void goGetHerSon() {
    // Get Plugin
    RabbitMQPlugin plugin = Play.plugin(RabbitMQPlugin.class);

    // Define Channel
    Channel channel = null;
    QueueingConsumer consumer = null;
    Long deliveryTag = null;

    // Get Channel
    while (true) {
        // Log Debug
        Logger.info("Entering main loop on consumer: " + this);

        // Are Consumers Running?
        boolean active = RabbitMQPlugin.areConsumersActive();

        // Only do work if consumers are running
        if (active) {
            try {
                // Create Channel
                if (channel == null || (channel != null && channel.isOpen() == false)) {
                    consumer = null;
                    channel = this.createChannel(plugin);
                }

                // Create Consumer
                if (consumer == null) {
                    consumer = this.createConsumer(channel, plugin);
                }

                // Get Task
                QueueingConsumer.Delivery task = consumer.nextDelivery();

                // Date Night
                if ((task != null) && (task.getBody() != null)) {
                    try {
                        // Fire job that will pass the message to the
                        // consumer,
                        // ack the queue and do the retry logic
                        deliveryTag = task.getEnvelope().getDeliveryTag();
                        T message = this.toObject(task.getBody());
                        new RabbitMQMessageConsumerJob(channel, deliveryTag, this.queue(), this, message,
                                this.retries()).doJobWithResult();

                    } catch (Throwable t) {
                        // Handle Exception
                        Logger.error(ExceptionUtil.getStackTrace(t));
                    }

                }

            } catch (Throwable t) {
                Logger.error(
                        "Error creating consumer channel to RabbitMQ, retrying in a few seconds. Exception: %s",
                        ExceptionUtil.getStackTrace(t));
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    Logger.error(ExceptionUtil.getStackTrace(t));
                }

            } finally {
                if (channel != null) {
                    // Now tell Daddy everything is cool
                    try {
                        if (deliveryTag != null && channel.isOpen()) {
                            channel.basicAck(deliveryTag, false);
                        }
                    } catch (Throwable e) {
                        Logger.error(ExceptionUtil
                                .getStackTrace("Error doing a basicAck for tag: " + deliveryTag, e));
                    }
                    try {
                        if (channel.getConnection() != null && channel.getConnection().isOpen()) {
                            channel.getConnection().close();
                        }
                        if (channel.isOpen() == true) {
                            channel.close();
                        }
                    } catch (Throwable t) {
                        Logger.error(ExceptionUtil.getStackTrace(t));
                    } finally {
                        channel = null;
                    }
                }
            }
        } else {
            Logger.warn("RabbitMQ consumers are paused and napping for 10 secs...");
            try {
                Thread.sleep(10000);
            } catch (Throwable t) {
            }
        }
    }
}

From source file:scratchpad.SimpleConsumer.java

License:Mozilla Public License

public static void main(String[] args) {
    try {/*from ww w .j  a va  2  s  .  c  o m*/
        String hostName = (args.length > 0) ? args[0] : "localhost";
        int portNumber = (args.length > 1) ? Integer.parseInt(args[1]) : AMQP.PROTOCOL.PORT;
        String queueName = (args.length > 2) ? args[2] : "eventName";

        ConnectionFactory connFactory = new ConnectionFactory();
        connFactory.setHost(hostName);
        connFactory.setPort(portNumber);
        Connection conn = connFactory.newConnection();

        final Channel ch = conn.createChannel();

        ch.queueDeclare();

        QueueingConsumer consumer = new QueueingConsumer(ch);
        ch.basicConsume(queueName, consumer);
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            Envelope envelope = delivery.getEnvelope();
            System.out
                    .println("Routing Key: " + envelope.getRoutingKey() + ":" + new String(delivery.getBody()));
            ch.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }
    } catch (Exception ex) {
        System.err.println("Main thread caught exception: " + ex);
        ex.printStackTrace();
        System.exit(1);
    }
}

From source file:taucalcworker.TaucalcWorker.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException/*from  www  . j a  va 2s.c  o  m*/
 * @throws java.util.concurrent.TimeoutException
 */
public static void main(String[] args) throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare(WORKQUEUENAME, false, false, false, null);
    channel.queueDeclare(RESULTQUEUENAME, false, false, false, null);
    channel.basicQos(1);

    byte[] inputbyte = { 0, 0, 0, 0 };
    String input = "";

    do {
        if (System.in.available() > 0) {
            System.in.read(inputbyte);
            input = new String(inputbyte);
        }
        GetResponse response = channel.basicGet(WORKQUEUENAME, false);
        if (response != null) {
            long deliverytag = response.getEnvelope().getDeliveryTag();
            byte[] body = response.getBody();
            int tries = ByteBuffer.wrap(body).getInt();
            System.out.println("Task received: " + tries);
            int success = 0;
            for (int i = 0; i < tries; i++) {
                double x = Math.random();
                double y = Math.random();
                if (x * x + y * y <= 1) {
                    success++;
                }
            }
            System.out.println("success: " + success + " out of " + tries);
            double tau = ((double) success / tries) * 8;
            System.out.println("Tau = " + tau);
            byte[] resultbytes = new byte[8];
            ByteBuffer.wrap(resultbytes).putDouble(tau);
            channel.basicPublish("", RESULTQUEUENAME, null, resultbytes);
            channel.basicAck(deliverytag, false);
        }
    } while (!input.equals("stop"));
    channel.close();
    connection.close();
    System.out.println("You stopped the program.");
}

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

License:Open Source License

public void cleanQueue(String queue, String match) throws IOException, InterruptedException {
    logger.trace(queue.concat(": ").concat(match));
    Connection connectionRcv = getRmqConn();
    Channel channel = connectionRcv.createChannel();
    channel.queueDeclare(queue, true, false, false, null);

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue, false, consumer);
    QueueingConsumer.Delivery delivery = consumer.nextDelivery(1000);
    Set seen = new HashSet();
    while (delivery != null) {
        String body = new String(delivery.getBody());
        if (seen.contains(body)) {
            break;
        }/*from w ww  .j  av  a  2  s  .c o  m*/
        if (body.contains(match)) {
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        } else {
            channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, true);
            seen.add(body);
        }
        delivery = consumer.nextDelivery(1000);
    }
    channel.close();
    closeRmqConn(connectionRcv);
}

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

License:Open Source License

public List<File> getFiles(String queue, Path outFolder, boolean ack) throws IOException, InterruptedException {
    List files = new ArrayList();
    Connection connectionRcv = getRmqConn();
    Channel channel = connectionRcv.createChannel();
    channel.queueDeclare(queue, true, false, false, null);

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue, false, consumer);
    QueueingConsumer.Delivery delivery = consumer.nextDelivery(1000);

    Set seen = new HashSet();

    while (delivery != null) {
        String host = delivery.getProperties().getHeaders().get("host").toString();
        File outTo = Paths.get(outFolder.toString(), host + ".tar.gz").toFile();
        FileUtils.writeByteArrayToFile(outTo, delivery.getBody());
        if (ack) {
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        } else {//from ww  w . ja  va 2s.c  o  m
            channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, true);
        }
        if (seen.contains(delivery.getProperties().getHeaders().get("host"))) {
            break;
        }
        seen.add(delivery.getProperties().getHeaders().get("host"));
        files.add(outTo);
        logger.info(queue + " retrieved: " + outTo.getAbsolutePath());
        delivery = consumer.nextDelivery(1000);
    }
    logger.warn("getFiles done");
    channel.close();
    closeRmqConn(connectionRcv);
    return files;
}

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

License:Open Source License

public WorkerState getWorkerState(String queue, long wait) throws IOException, InterruptedException {
    WorkerState ws = null;/*from w w  w.  jav  a 2s .  co m*/
    Connection connectionRcv = getRmqConn();
    Channel channel = connectionRcv.createChannel();
    channel.queueDeclare(queue, true, false, false, null);

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue, false, consumer);
    QueueingConsumer.Delivery delivery;
    if (wait == -1) {
        delivery = consumer.nextDelivery(); // will block until response
    } else {
        delivery = consumer.nextDelivery(wait);
    }
    if (delivery != null) {
        String message = new String(delivery.getBody());
        ws = (WorkerState) Utils.jsonToObject(message, WorkerState.class);
        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }
    channel.close();
    closeRmqConn(connectionRcv);
    return ws;
}

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

License:Open Source License

/**
 * Gets a single message from a queue, ideal for getting an item of work.
 * @param queue//from w w w.  j  a v  a2s.  co m
 * @param wait
 * @return A JSON string representing an object, you need to know what type of object the queue will return and handle this outside of here
 * @throws IOException
 * @throws InterruptedException 
 */
public String getMessageString(String queue, long wait) throws IOException, InterruptedException {
    String message = null;
    Connection connectionRcv = getRmqConn();
    Channel channel = connectionRcv.createChannel();
    channel.queueDeclare(queue, true, false, false, null);

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue, false, consumer);
    QueueingConsumer.Delivery delivery;
    if (wait == -1) {
        delivery = consumer.nextDelivery(); // will block until response
    } else {
        delivery = consumer.nextDelivery(wait);
    }
    if (delivery != null) {
        message = new String(delivery.getBody());
        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        logger.info(queue + " recieved: " + message);
    }
    channel.close();
    closeRmqConn(connectionRcv);
    return message;
}

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

License:Open Source License

public void removeFromStateQueue(String queue, String hostToRemove) throws IOException, InterruptedException {
    logger.trace(queue.concat(": ").concat(hostToRemove));
    Connection connectionRcv = getRmqConn();
    Channel channel = connectionRcv.createChannel();
    int maxTries = channel.queueDeclare(queue, true, false, false, null).getMessageCount();
    logger.trace("Queue : messages\t" + queue + " : " + maxTries);

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue, false, consumer);
    QueueingConsumer.Delivery delivery = consumer.nextDelivery(200);
    logger.trace(maxTries);/*  w w w. j  a v  a2 s.  co  m*/
    while (delivery != null && maxTries > 0) {
        // the toString in the middle of this is needed as it is wrapped with another type that can hold 4GB
        Map<String, Object> headers = delivery.getProperties().getHeaders();
        if (headers != null && headers.get("host").toString().equals(hostToRemove)) {
            logger.trace(headers.get("host").toString().concat(" remove"));
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        } else {
            channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, true);
        }
        delivery = consumer.nextDelivery(200);
        maxTries--;
    }
    channel.close();
    closeRmqConn(connectionRcv);
}

From source file:wiki.messaging.Receive.java

License:Open Source License

public static void main(String[] args) throws IOException, InterruptedException {
    String url = null;//from   w w  w . jav  a 2  s  .  com
    String rabbitMqUrl = null;
    for (int i = 0; i < args.length; i++) {
        if (args[i].equals("ds")) {
            url = args[i + 1];
        } else if (args[i].equals("rq")) {
            rabbitMqUrl = args[i + 1];
        } else if (args[i].equals("mj")) {
            maxJobs = Integer.valueOf(args[i + 1]);
        }
    }
    if (rabbitMqUrl == null) {
        rabbitMqUrl = "192.168.1.108";
    }
    if (url == null) {
        url = "localhost";
    }
    //        if (resultUrl == null) {
    //            resultUrl = url;
    //        }
    threadPool = new ExecutorCompletionService<>(Executors.newFixedThreadPool(maxJobs));
    System.out.println("DataSource: " + url);
    //        System.out.println("ResultWrite: " + resultUrl);
    DbConnector ds = new DbConnector(url);
    //        DbConnector rs = new DbConnector(resultUrl);

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(rabbitMqUrl);
    factory.setUsername("wiki");
    factory.setPassword("wiki");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    channel.queueDeclare(RESULT_QUEUE_NAME, true, false, false, null);
    System.out.println(" [*] Waiting for messages.");

    channel.basicQos(maxJobs);

    QueueingConsumer consumer = new QueueingConsumer(channel);
    boolean autoAck = false;
    channel.basicConsume(QUEUE_NAME, autoAck, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        String message = new String(delivery.getBody());
        System.out.println(" [x] Received '" + message + "'");
        doWork(message, ds);
        saveResult(channel);
        System.out.println(" [x] Done");
        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }
}

From source file:wiki.messaging.ResultConsumer.java

License:Open Source License

public static void main(String[] args) throws IOException, InterruptedException {
    String rabbitMqUrl = null;/*from ww w. ja va 2 s  .c o  m*/
    String resultUrl = null;
    for (int i = 0; i < args.length; i++) {
        if (args[i].equals("rs")) {
            resultUrl = args[i + 1];
        } else if (args[i].equals("rq")) {
            rabbitMqUrl = args[i + 1];
        }
    }

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(rabbitMqUrl);
    factory.setUsername("wiki");
    factory.setPassword("wiki");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(RESULT_QUEUE_NAME, true, false, false, null);
    System.out.println(" [*] Waiting for messages.");

    QueueingConsumer consumer = new QueueingConsumer(channel);
    boolean autoAck = false;
    channel.basicConsume(RESULT_QUEUE_NAME, autoAck, consumer);

    DbConnector dbc = new DbConnector(resultUrl);

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery(1000);
        if (delivery == null)
            break;
        String message = new String(delivery.getBody());
        System.out.println(" [x] Received '" + message + "'");
        saveResult(message, dbc);
        System.out.println(" [x] Done");
        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }
    channel.close();
    connection.close();
}