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, boolean noLocal, boolean exclusive,
        Map<String, Object> arguments, Consumer callback) throws IOException;

Source Link

Document

Start a consumer.

Usage

From source file:com.kurento.kmf.rabbitmq.RabbitTemplate.java

License:Apache License

protected Message doSendAndReceiveWithTemporary(final String exchange, final String routingKey,
        final Message message) {
    return this.execute(new ChannelCallback<Message>() {

        @Override/*  w w w.jav a 2s.c om*/
        public Message doInRabbit(Channel channel) throws Exception {
            final ArrayBlockingQueue<Message> replyHandoff = new ArrayBlockingQueue<Message>(1);

            Assert.isNull(message.getMessageProperties().getReplyTo(),
                    "Send-and-receive methods can only be used if the Message does not already have a replyTo property.");
            DeclareOk queueDeclaration = channel.queueDeclare();
            String replyTo = queueDeclaration.getQueue();
            message.getMessageProperties().setReplyTo(replyTo);

            String consumerTag = UUID.randomUUID().toString();
            DefaultConsumer consumer = new DefaultConsumer(channel) {

                @Override
                public void handleDelivery(String consumerTag, Envelope envelope,
                        AMQP.BasicProperties properties, byte[] body) throws IOException {
                    MessageProperties messageProperties = messagePropertiesConverter
                            .toMessageProperties(properties, envelope, encoding);
                    Message reply = new Message(body, messageProperties);
                    if (logger.isTraceEnabled()) {
                        logger.trace("Message received " + reply);
                    }
                    try {
                        replyHandoff.put(reply);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
            };
            channel.basicConsume(replyTo, true, consumerTag, true, true, null, consumer);
            doSend(channel, exchange, routingKey, message, null);
            Message reply = (replyTimeout < 0) ? replyHandoff.take()
                    : replyHandoff.poll(replyTimeout, TimeUnit.MILLISECONDS);
            channel.basicCancel(consumerTag);
            return reply;
        }
    });
}

From source file:net.es.netshell.rabbitmq.Box.java

License:Open Source License

public Queue createQueue(String symLink, Channel channel) throws Exception {
    String queueName = UUID.randomUUID().toString();
    channel.queueDeclare(queueName, false, false, true, null);
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, true, symLink, false, false, null, consumer);

    return new Queue(queueName, symLink);
}

From source file:net.es.netshell.rabbitmq.Box.java

License:Open Source License

public String queryQueue(String sendQueue, String token, Channel channel, String symLink) throws Exception {

    // Create random UUID for producer's temporary queue
    String uuid = UUID.randomUUID().toString();
    // Declare this temporary queue and start listening (exclusive queue).
    channel.queueDeclare(uuid, false, true, true, null);
    QueueingConsumer consumer = new QueueingConsumer(channel);

    // Send TOKEN_REQUEST with curent username.
    String message = token + ":QUEUE_QUERY" + ":" + uuid + ":"
            + KernelThread.currentKernelThread().getUser().getName() + ":" + symLink;

    channel.basicPublish("", sendQueue, null, message.getBytes());
    // Start consuming to receive token.
    channel.basicConsume(uuid, true, "tokenRequest", false, true, null, consumer);
    QueueingConsumer.Delivery delivery = consumer.nextDelivery();

    // When token is received, store in "token."
    String queueName = new String(delivery.getBody());
    // Delete temporary queue
    channel.queueDelete(uuid);/*from   w w  w .j  a v a  2 s .  co m*/

    return queueName;

}

From source file:net.es.netshell.rabbitmq.Consume.java

License:Open Source License

public void consumeMessage() throws Exception {
    if (queueName == null) {
        queueName = new UUIDManager(QUEUE_FILE).checkUUID();
    }/*from   w  ww .  j a  v  a  2 s . co m*/
    ConnectionFactory factory = new SSLConnection(info).createConnection();
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

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

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, true, "consumer", false, false, null, consumer);

    //while (true) {
    QueueingConsumer.Delivery delivery = consumer.nextDelivery();
    ByteArrayInputStream bais = new ByteArrayInputStream(delivery.getBody());
    ObjectInputStream in = new ObjectInputStream(bais);
    DefaultListenableGraph g = (DefaultListenableGraph) in.readObject();
    System.out.println(" [x] Received Message");

    // GraphViewer view = new GraphViewer(g);
    // view.init();

    //         if (message.substring(0,13).equals("TOKEN_REQUEST")) {
    //            String[] token = new ProcessTokenRequest(message, channel).sendToken();
    //            permissions.put(token[0], token[1]);
    //            //String[] messageSplit = message.split(":");
    //            //sendToken(messageSplit[1], messageSplit[2], channel);
    //         } else {
    //            String[] messageSplit = message.split(":", 2);
    //            if (permissions.containsKey(messageSplit[0])) {
    //               System.out.println(" [x] Received '" + messageSplit[1] + "' from: " + permissions.get(messageSplit[0]));
    //            } else {
    //               System.out.println(" ERROR: INVALID TOKEN PROVIDED IN MESSAGE");
    //            }
    //         }
    //}

    channel.queueDelete(queueName);
    channel.close();
    connection.close();
}

From source file:net.es.netshell.rabbitmq.CreateToken.java

License:Open Source License

public CreateToken(BrokerInfo info, Channel tokenChannel, String listenerID) throws Exception {
    // Info on data needed to create a connection
    this.info = info;

    // Create random UUID for producer's temporary queue
    String uuid = UUID.randomUUID().toString();
    // Declare this temporary queue and start listening (exclusive queue).
    tokenChannel.queueDeclare(uuid, false, true, true, null);
    QueueingConsumer consumer = new QueueingConsumer(tokenChannel);

    // Send TOKEN_REQUEST with current username.
    String message = "TOKEN_REQUEST" + ":" + uuid + ":"
            + KernelThread.currentKernelThread().getUser().getName();

    tokenChannel.basicPublish("", listenerID, null, message.getBytes());
    // Start consuming to receive token.
    tokenChannel.basicConsume(uuid, true, "tokenRequest", false, false, null, consumer);
    QueueingConsumer.Delivery delivery = consumer.nextDelivery();

    // When token is received, store in "token."
    token = new String(delivery.getBody());
    // Delete temporary queue
    tokenChannel.queueDelete(uuid);//w ww.  j av a 2  s  . c o m
}

From source file:org.springframework.amqp.rabbit.core.RabbitManagementTemplateTests.java

License:Apache License

@Test
public void testSpecificQueue() throws Exception {
    RabbitAdmin admin = new RabbitAdmin(connectionFactory);
    Map<String, Object> args = Collections.<String, Object>singletonMap("foo", "bar");
    Queue queue1 = QueueBuilder.nonDurable(UUID.randomUUID().toString()).autoDelete().withArguments(args)
            .build();// ww  w.  j a  v a2s  .c  om
    admin.declareQueue(queue1);
    Queue queue2 = QueueBuilder.durable(UUID.randomUUID().toString()).withArguments(args).build();
    admin.declareQueue(queue2);
    Channel channel = this.connectionFactory.createConnection().createChannel(false);
    String consumer = channel.basicConsume(queue1.getName(), false, "", false, true, null,
            new DefaultConsumer(channel));
    QueueInfo qi = this.template.getClient().getQueue("/", queue1.getName());
    int n = 0;
    while (n++ < 100 && (qi.getExclusiveConsumerTag() == null || qi.getExclusiveConsumerTag().equals(""))) {
        Thread.sleep(100);
        qi = this.template.getClient().getQueue("/", queue1.getName());
    }
    Queue queueOut = this.template.getQueue("/", queue1.getName());
    assertFalse(queueOut.isDurable());
    assertFalse(queueOut.isExclusive());
    assertTrue(queueOut.isAutoDelete());
    assertEquals(queue1.getName(), queueOut.getName());
    assertEquals(args, queueOut.getArguments());
    assertEquals(consumer, qi.getExclusiveConsumerTag());
    channel.basicCancel(consumer);
    channel.close();

    queueOut = this.template.getQueue("/", queue2.getName());
    assertTrue(queueOut.isDurable());
    assertFalse(queueOut.isExclusive());
    assertFalse(queueOut.isAutoDelete());
    assertEquals(queue2.getName(), queueOut.getName());
    assertEquals(args, queueOut.getArguments());

    admin.deleteQueue(queue1.getName());
    admin.deleteQueue(queue2.getName());
}

From source file:org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer.java

License:Apache License

private void doConsumeFromQueue(String queue) {
    if (!isActive()) {
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Consume from queue " + queue + " ignore, container stopping");
        }/* w  ww . jav  a  2s .  com*/
        return;
    }
    Connection connection = null; // NOSONAR (close)
    try {
        connection = getConnectionFactory().createConnection();
    } catch (Exception e) {
        this.consumersToRestart.add(new SimpleConsumer(null, null, queue));
        throw new AmqpConnectException(e);
    }
    Channel channel = null;
    SimpleConsumer consumer = null;
    try {
        channel = connection.createChannel(isChannelTransacted());
        channel.basicQos(getPrefetchCount());
        consumer = new SimpleConsumer(connection, channel, queue);
        channel.queueDeclarePassive(queue);
        consumer.consumerTag = channel.basicConsume(queue, getAcknowledgeMode().isAutoAck(),
                (getConsumerTagStrategy() != null ? getConsumerTagStrategy().createConsumerTag(queue) : ""),
                false, isExclusive(), getConsumerArguments(), consumer);
    } catch (IOException e) {
        RabbitUtils.closeChannel(channel);
        RabbitUtils.closeConnection(connection);

        if (e.getCause() instanceof ShutdownSignalException
                && e.getCause().getMessage().contains("in exclusive use")) {
            getExclusiveConsumerExceptionLogger().log(logger, "Exclusive consumer failure", e.getCause());
            publishConsumerFailedEvent("Consumer raised exception, attempting restart", false, e);
        } else if (this.logger.isDebugEnabled()) {
            this.logger.debug("Queue not present or basicConsume failed, scheduling consumer " + consumer
                    + " for restart");
        }
        this.consumersToRestart.add(consumer);
        consumer = null;
    }
    synchronized (this.consumersMonitor) {
        if (consumer != null) {
            this.cancellationLock.add(consumer);
            this.consumers.add(consumer);
            this.consumersByQueue.add(queue, consumer);
            if (this.logger.isInfoEnabled()) {
                this.logger.info(consumer + " started");
            }
        }
    }
}