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:reactor.rabbitmq.SenderTests.java

License:Open Source License

@Test
void createExchangeBeforePublishing() throws Exception {
    int nbMessages = 10;
    CountDownLatch latch = new CountDownLatch(nbMessages);
    AtomicInteger counter = new AtomicInteger();
    Channel channel = connection.createChannel();
    channel.basicConsume(queue, true, new DefaultConsumer(channel) {

        @Override// ww  w . j  ava 2  s. c om
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            counter.incrementAndGet();
            latch.countDown();
        }
    });

    String exchange = UUID.randomUUID().toString();

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

    sender = createSender();
    sender.declare(ExchangeSpecification.exchange(exchange).type("direct").autoDelete(true))
            .then(sender.bind(BindingSpecification.binding(exchange, queue, queue))).then(sender.send(msgFlux))
            .subscribe();
    assertTrue(latch.await(1, TimeUnit.SECONDS));
    assertEquals(nbMessages, counter.get());
}

From source file:Release1.Controllers.AlarmController.java

/**
 * mtodo para recibir mensajes de los sensores de alarmas de ventana
 * dependiendo del mensaje recibido se envia la respuesta a los sensores
 * @throws IOException// w  w  w  . j av a 2  s.co  m
 * @throws TimeoutException 
 */
private synchronized void receiveAlamrWindowSensorMessage() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(HOST);

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

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

    Consumer consumer;
    consumer = new DefaultConsumer(channel) {
        @Override
        public synchronized void handleDelivery(String consumerTag, Envelope envelope,
                AMQP.BasicProperties properties, byte[] body) throws IOException {
            setMessage(new String(body, "UTF-8"));
            logger.info("Class ALARM WINDOW Controller --- RECEIVED from Sensor --- Value: "
                    + new String(body, "UTF-8"));
            if (Integer.parseInt(getMessage()) > MAX_VALUE_ALARMS) {//si el valor obtenido es mayor al permitido para simular las alarmas se activa la alarma
                try {
                    sendMessage(ID_CHANNEL_AWINDOW_CONTROLLER, ID_AWINDOW_ON);//envio de mensaje para encender alarma la alarma de ventnaa
                    logger.info("Class: ALARM CONTROLLER --- SEND --- ACTIVE ALARM WINDOW");
                } catch (TimeoutException ex) {
                    logger.error(ex);
                }
            } else {
                try {
                    sendMessage(ID_CHANNEL_AWINDOW_CONTROLLER, ID_AWINDOW_OFF);//envio de mensaje apra apagar la alarma de ventana
                } catch (TimeoutException ex) {
                    logger.error(ex);
                }
            }
        }
    };
    channel.basicConsume(queueName, true, consumer);
}

From source file:Release1.Controllers.AlarmController.java

/**
 * mtodo para recibir mensajes de los sensores de alarmas de puerta
 * dependiendo del mensaje recibido se envia la respuesta a los sensores
 * @throws IOException//  w  w  w .  j  a  va2  s.c  o m
 * @throws TimeoutException 
 */
private void receiveAlarmDoorMessage() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(HOST);
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

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

    Consumer consumer = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            setMessage(new String(body, "UTF-8"));
            logger.info("Class Alarm DOOR Controller --- RECEIVED from Sensor --- Value: "
                    + new String(body, "UTF-8"));
            if (Integer.parseInt(getMessage()) > MAX_VALUE_ALARMS) {
                try {
                    sendMessage(ID_CHANNEL_ADOOR_CONTROLLER, ID_ADOOR_ON);//envio de mensaje para encender la alarma
                } catch (TimeoutException ex) {
                    logger.error(ex);
                }
            } else {
                try {
                    sendMessage(ID_CHANNEL_ADOOR_CONTROLLER, ID_ADOOR_OFF);//envio de mensajes para apagar la alarma
                } catch (TimeoutException ex) {
                    logger.error(ex);
                }
            }
        }
    };
    channel.basicConsume(queueName, true, consumer);
}

From source file:Release1.Controllers.AlarmController.java

/**
 * * mtodo para recibir mensajes de los sensores de alarmas de movimiento
 * dependiendo del mensaje recibido se envia la respuesta a los sensores
 * @throws IOException//from  w  w  w .ja v a  2  s. com
 * @throws TimeoutException 
 */
private void receiveMoveMessage() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(HOST);

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

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

    Consumer consumer;
    consumer = new DefaultConsumer(channel) {
        @Override
        public synchronized void handleDelivery(String consumerTag, Envelope envelope,
                AMQP.BasicProperties properties, byte[] body) throws IOException {
            setMessage(new String(body, "UTF-8"));
            logger.info("Class ALARM MOVE Controller --- RECEIVED from Sensor --- Value: "
                    + new String(body, "UTF-8"));
            if (Integer.parseInt(getMessage()) > MAX_VALUE_ALARMS) {
                try {
                    sendMessage(ID_CHANNEL_AMOVE_CONTROLLER, ID_AMOVE_ON);//envio de mensajes para encender la alarma de movimiento
                    logger.info("Class: ALARM CONTROLLER --- SEND --- ACTIVE ALARM WINDOW");
                } catch (TimeoutException ex) {
                    logger.error(ex);
                }
            } else {
                try {
                    sendMessage(ID_CHANNEL_AMOVE_CONTROLLER, ID_AMOVE_OFF);//envio de mensajes para apagar la alarma de movimientos
                } catch (TimeoutException ex) {
                    logger.error(ex);
                }
            }
        }
    };
    channel.basicConsume(queueName, true, consumer);
}

From source file:Release2.Controllers.AlarmFireController.java

private synchronized void receivedAlarmFireSensorMessage() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(HOST);//from  ww w  .ja  v  a  2s  . c  o  m

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

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

    Consumer consumer;
    consumer = new DefaultConsumer(channel) {
        @Override
        public synchronized void handleDelivery(String consumerTag, Envelope envelope,
                AMQP.BasicProperties properties, byte[] body) throws IOException {
            setMessage(new String(body, "UTF-8"));
            logger.info("Class ALARM FIRE Controller --- RECEIVED from Sensor --- Value: "
                    + new String(body, "UTF-8"));
            if (Integer.parseInt(getMessage()) > MAX_VALUE_ALARMS) {//si el valor obtenido es mayor al permitido para simular las alarmas se activa la alarma
                try {
                    sendMessage(ID_CHANNEL_AFIRE_CONTROLLER, ID_AFIRE_ON);//envio de mensaje para encender alarma la alarma de ventnaa
                    logger.info("Class: ALARM CONTROLLER --- SEND --- ACTIVE ALARM WINDOW");
                } catch (TimeoutException ex) {
                    logger.error(ex);
                }
            } else {
                try {
                    sendMessage(ID_CHANNEL_AFIRE_CONTROLLER, ID_AFIRE_OFF);//envio de mensaje apra apagar la alarma de ventana
                } catch (TimeoutException ex) {
                    logger.error(ex);
                }
            }
        }
    };
    channel.basicConsume(queueName, true, consumer);
}

From source file:samples.userguide.RabbitMQAMQPClient.java

License:Apache License

public static void main(String[] args) {
    String queueName = System.getProperty("queueName");
    String mode = System.getProperty("mode");
    String routingKey = System.getProperty("routingKey");
    String exchangeName = System.getProperty("exchangeName");

    String quote = System.getProperty("payLoad");
    if (quote == null) {
        quote = "IBM";
    }/*from   w  w w . ja v  a2s. c  o  m*/
    String msg = "<m:placeOrder xmlns:m=\"http://services.samples\">\n" + "    <m:order>\n"
            + "        <m:price>" + getRandom(100, 0.9, true) + "</m:price>\n" + "        <m:quantity>"
            + (int) getRandom(10000, 1.0, true) + "</m:quantity>\n" + "        <m:symbol>" + quote
            + "</m:symbol>\n" + "    </m:order>\n" + "</m:placeOrder>";

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

        if (mode == null) {
            mode = "producer";
        }

        if ("producer".equals(mode)) {
            if (queueName != null) {
                channel.basicPublish("", queueName, null, msg.getBytes());
            } else {
                if (routingKey != null) {
                    if (exchangeName == null) {
                        exchangeName = "topic-exchange";
                    }
                    channel.basicPublish(exchangeName, routingKey, null, msg.getBytes());

                } else {
                    if (exchangeName == null) {
                        exchangeName = "subscriber-exchange";
                    }
                    channel.basicPublish(exchangeName, "", null, msg.getBytes());
                }
            }
        } else {
            if (queueName == null) {
                queueName = "ConsumerProxy";
            }
            QueueingConsumer consumer = new QueueingConsumer(channel);
            channel.basicConsume(queueName, true, consumer);

            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            System.out.println("[x] received '" + message + "'");
        }
        channel.close();
        connection.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        if (channel != null && channel.isOpen()) {
            try {
                channel.close();
            } catch (IOException e) {
                System.err.println("Error occurred while closing the channel:" + e.getMessage());
            }
        }
        if (connection != null && connection.isOpen()) {
            try {
                connection.close();
            } catch (IOException e) {
                System.err.println("Error occurred while closing the connection:" + e.getMessage());
            }
        }
    }
}

From source file:se.kodiak.logging.appenders.util.MQListener.java

License:Open Source License

public MQListener() {
    try {/*www  .ja  va2  s .  c  o  m*/
        ConnectionFactory factory = new ConnectionFactory();
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.basicQos(1);
        channel.exchangeDeclare("test", "topic");
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, "test", "log.*");
        consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, true, consumer);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:server.Worker.java

License:Open Source License

/**
 * @param args/*w  w w. j  av  a2 s. c  o  m*/
 * @throws IOException
 * @throws TimeoutException
 */
public static void main(String[] args) throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection requestConnection = factory.newConnection();
    Channel requestChannel = requestConnection.createChannel();
    requestChannel.queueDeclare(REQUEST_QUEUE_NAME, false, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    Connection responseConnection = factory.newConnection();
    final Channel responseChannel = responseConnection.createChannel();
    responseChannel.queueDeclare(RESPONSE_QUEUE_NAME, false, false, false, null);

    Consumer consumer = new DefaultConsumer(requestChannel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            PriorityRequest request = (PriorityRequest) SerializationUtils.deserialize(body);
            System.out.println(" [x] Received");
            System.out.println(request.request.toString());
            System.out.println("*************************************");

            System.out.println(request.request.getMethod());
            HttpResponse response = PluginManager.getInstance().process(request.request, request.rootDir);
            if (response == null) {
                response = HttpResponseFactory.create400BadRequest(Protocol.CLOSE);
            }
            try {
                System.out.println(request.id);
            } catch (Exception e) {
                e.printStackTrace();
            }

            response.id = request.id;

            byte[] data = SerializationUtils.serialize(response);
            responseChannel.basicPublish("", RESPONSE_QUEUE_NAME, null, data);
        }
    };
    requestChannel.basicConsume(REQUEST_QUEUE_NAME, true, consumer);
}

From source file:src.main.java.server.MsgReceiveServer.java

public MsgReceiveServer(int SERVER_PORT, String logDirname, String zipDirname, String dbUser, String dbPwd,
        boolean withLog) throws IOException, TimeoutException, JSONException {

    super(SERVER_PORT);

    this.withLog = withLog;
    this.logDir = logDirname;
    this.zipDir = zipDirname;

    dataSource = new DataSource(dbUser, dbPwd);

    HashMap<String, Message> user2msg;
    allMsg = new HashMap<String, HashMap<String, Message>>();
    ArrayList<Pair<String, String>> res = dataSource.getGroupUser();
    for (Pair<String, String> p : res) {
        msg = new Message("{}", p.getR());
        msg.init(p.getR(), "localhost");
        msg.bindTo(p.getL(), p.getR());/*from w w w.j  a va 2  s . co  m*/
        if (allMsg.containsKey(p.getL())) {
            allMsg.get(p.getL()).put(p.getR(), msg);
        } else {
            user2msg = new HashMap<String, Message>();
            user2msg.put(p.getR(), msg);
            allMsg.put(p.getL(), user2msg);
        }
    }

    loginMsg = new Message("{}", "");
    loginMsg.init("login_request", "localhost");
    loginMsg.bindTo("login_auth", "login_request");

    normalMsg = new Message("{}", "");
    normalMsg.init("normal_msg", "localhost");
    normalMsg.bindTo("msg_send", "normal_msg");

    logoutMsg = new Message("{}", "");
    logoutMsg.init("logout_msg", "localhost");
    logoutMsg.bindTo("msg_send", "logout_msg");

    reloginMsg = new Message("{}", "");
    reloginMsg.init("relogin_msg", "localhost");
    reloginMsg.bindTo("msg_send", "relogin_msg");

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel loginSuccessChannel = connection.createChannel();
    loginSuccessChannel.queueDeclare("login_success", true, false, false, null);
    loginSuccessConsumer = new DefaultConsumer(loginSuccessChannel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String sLoginSuccessMsg = new String(body, "UTF-8");
            try {
                Message loginSuccessMsg = new Message("{}", "");
                loginSuccessMsg.reset(sLoginSuccessMsg);
                String loginSuccessUsername = loginSuccessMsg.getValue("username");
                if (user_list.contains(loginSuccessUsername) == false) {
                    user_list.add(loginSuccessUsername);
                }
                System.out.println(user_list.size());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };
    loginSuccessChannel.basicConsume("login_success", true, loginSuccessConsumer);

}

From source file:translators.ToJsonSchool.java

public static void main(String[] args) throws Exception {
    final String replyQueueName = "teachersJsonReply";
    final String EXCHANGE_NAME_SCHOOL = "cphbusiness.bankJSON";
    final String exchangeName = ExchangeName.GLOBAL;

    RabbitConnection rabbitConnection = new RabbitConnection();

    Channel channel = rabbitConnection.makeConnection();

    channel.exchangeDeclare(exchangeName, "direct");
    String queueName = channel.queueDeclare().getQueue();

    channel.queueBind(queueName, exchangeName, "keyBankJSON");

    //get banks from queue. "Get banks" component
    QueueingConsumer consumer = new QueueingConsumer(channel) {
        @Override// w  ww.ja  v  a2s .c o  m
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            System.out.println("Received msg: " + message);
            Message messageFromJson = getFromJson(message);

            sendMsgToBank(messageFromJson, properties.getCorrelationId(), EXCHANGE_NAME_SCHOOL, replyQueueName);
        }
    };
    channel.basicConsume(queueName, true, consumer);
}