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, Consumer callback) throws IOException;

Source Link

Document

Start a non-nolocal, non-exclusive consumer, with a server-generated consumerTag.

Usage

From source file:com.UseCaseSimpleProducer.java

License:Open Source License

public static void main(String[] argv) throws java.io.IOException, InterruptedException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    try {/* w  w w. j  a va 2  s .  com*/
        channel.exchangeDeclarePassive(EXCHANGE_NAME);
    } catch (java.io.IOException e) {
        channel.exchangeDeclare(EXCHANGE_NAME, "direct");
    }

    try {
        channel.queueDeclarePassive(QUEUE_NAME);
    } catch (java.io.IOException e) {
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    }
    channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, QUEUE_NAME);

    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(QUEUE_NAME, true, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        String message = new String(delivery.getBody());
        System.out.println(" [x] Received '" + message + "'");
    }
}

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./*  w w w .  ja  v  a 2s  . 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.vmware.vhadoop.vhm.rabbit.RabbitConnection.java

License:Open Source License

QueueingConsumer getConsumer() throws CannotConnectException {
    synchronized (_consumerLock) {
        if (_consumer == null) {
            _log.fine("Creating new consumer");
            try {
                Channel channel = getChannel();
                _consumer = new QueueingConsumer(channel) {
                    @Override//w  ww . j ava2s .c  o m
                    public void handleShutdownSignal(java.lang.String consumerTag,
                            ShutdownSignalException sig) {
                        super.handleShutdownSignal(consumerTag, sig);
                        _log.info("Consumer received shutdown notification");
                        _log.log(Level.FINE, "{0}", sig.getReason());

                        synchronized (_consumerLock) {
                            _consumer = null;
                        }
                    }
                };
                channel.basicConsume(getQueueName(), true, _consumer);
            } catch (Exception e) {
                throw new CannotConnectException("Unable to get message consumer", e);
            }
        }

        return _consumer;
    }
}

From source file:com.wakkir.rabbitmq.basic.Reciever.java

public static void main(String[] argv) throws Exception {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

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

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(QUEUE_NAME, true, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        String message = new String(delivery.getBody(), "UTF-8");
        System.out.println(" [x] Received '" + message + "'");
    }//  w  w w .ja va2  s .com
}

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 {/* w ww . j  ava2  s .c  o m*/
            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);
            }
        }
    }
}

From source file:com.zigbee.function.util.MessageUtil.java

License:Open Source License

public static void reciveMessage(String queueName) {
    try {/*from w w  w.ja v  a 2  s.  co m*/
        Channel channel = openChannel(null);

        System.out.println(" [*] Waiting for messages");

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

        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            System.out.println(" Message Received '" + message + "'");
        }
    } catch (ShutdownSignalException e) {
        e.printStackTrace();
    } catch (ConsumerCancelledException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

From source file:controllerStuff.ControllerPublisher.java

private void attachControllerCallback(Controller controllerObject) {
    try {//www  . java 2  s.  co m

        Channel controllerCallbackChannel = connection.createChannel();
        controllerCallbackChannel.exchangeDeclare(EXCHANGE_CONTOLLER_CMD, "topic");
        String sensChName = controllerCallbackChannel.queueDeclare().getQueue();
        controllerCallbackChannel.queueBind(sensChName, EXCHANGE_CONTOLLER_CMD,
                BIND_KEY_BASE + nodeID + '.' + controllerObject.getName());

        System.out.println(BIND_KEY_BASE + nodeID + '.' + controllerObject.getName()); //Debug

        controllerCallbackChannel.basicConsume(sensChName, true,
                new DefaultConsumer(controllerCallbackChannel) {
                    @Override
                    public void handleDelivery(String consumerTag, Envelope envelope,
                            AMQP.BasicProperties properties, byte[] body) throws IOException {

                        controllerObject.call(new String(body, "UTF-8"));

                    }
                });

    } catch (IOException ex) {
        Logger.getLogger(ControllerPublisher.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:cs.rsa.ts14dist.appserver.RabbitMQDaemon.java

License:Apache License

@Override
public void run() {

    Connection connection = null;
    Channel channel = null;
    try {//from  w ww .jav a  2s. c om
        ConnectionFactory factory = new ConnectionFactory();
        logger.info("Starting RabbitMQDaemon, MQ IP = " + hostname);
        factory.setHost(hostname);

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

        channel.queueDeclare(rpcQueueName, false, false, false, null);

        channel.basicQos(1);

        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(rpcQueueName, false, consumer);

        while (true) {
            String response = null;

            // Block and fetch next msg from queue
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();

            BasicProperties props = delivery.getProperties();
            BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId())
                    .build();

            try {
                String message = new String(delivery.getBody(), "UTF-8");
                logger.trace("Received msg: " + message);

                // Convert the message to a JSON request object
                JSONObject request = (JSONObject) JSONValue.parse(message);

                // Delegate to the server request handler for handling the
                // request and computing an answer
                JSONObject reply = serverRequestHandler.handleRequest(request);

                // Convert the answer back into a string for replying to
                // client
                response = reply.toJSONString();
            } catch (Exception e) {
                logger.error(" Exception in MQDAemon run()/while true] " + e.toString());
                response = "wrong";
            } finally {
                logger.trace("Returning answer: " + response);
                channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes("UTF-8"));
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                logger.trace("Answer acknowledged.");
            }
        }
    } catch (Exception e) {
        logger.error("Exception in daemon's outer loop: nested exception" + e.getMessage());
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ignore) {
            }
        }
    }
}

From source file:dfki.sb.rabbitmqjava.RabbitMQObjectStreamServer.java

License:Open Source License

public static void main(String[] argv) {
    Channel channel = null;
    try {//  ww  w .ja  va  2 s. c o m
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
        channel.basicQos(1);
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
        System.out.println("Starting server waiting for client requests:");
        processSendAndRecivePackets(consumer, channel);
        if (argv != null && argv.length > 0 && argv[0].equalsIgnoreCase("infinite")) {
            while (true) {
                System.out.println("Waiting for next client");
                processSendAndRecivePackets(consumer, channel);
            }
        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException ignore) {
            }
        }
    }
}

From source file:dfki.sb.rabbitmqjava.RabbitMQServer.java

License:Open Source License

public static void main(String[] argv) {
    Connection connection = null;
    Channel channel = null;
    try {/*from w w  w  .j  av a  2s.c om*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
        channel.basicQos(1);
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
        System.out.println("Starting server waiting for client requests:");
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            BasicProperties props = delivery.getProperties();
            BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId())
                    .build();
            DataInputStream dis = new DataInputStream(
                    new BufferedInputStream(new ByteArrayInputStream(delivery.getBody())));
            try {
                int type = dis.readInt();
                byte[] response;
                if (type == 2) {
                    response = handleMarketRequest(dis);
                } else {
                    response = handleQuoteRequest(dis);
                }
                channel.basicPublish("", props.getReplyTo(), replyProps, response);
                dis.close();
            } catch (IOException | ClassNotFoundException e) {
                System.out.println(" [.] " + e.toString());
            } finally {
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        }
    } catch (IOException | InterruptedException | ShutdownSignalException | ConsumerCancelledException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException ignore) {
            }
        }
    }
}