Example usage for com.rabbitmq.client Channel queueDeclare

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

Introduction

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

Prototype

Queue.DeclareOk queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete,
        Map<String, Object> arguments) throws IOException;

Source Link

Document

Declare a queue

Usage

From source file:com.colm.app.Main.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Connection connection;//  w ww .  ja  va2s .c  om
    Channel channel;
    String replyQueueName;
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("192.168.0.13");
    factory.setPassword("admin");
    factory.setUsername("admin");
    factory.setVirtualHost("admin");
    connection = factory.newConnection();
    channel = connection.createChannel();
    String queneNAme = "rabbitmq_test";
    channel.queueDeclare(queneNAme, false, false, false, null);
    String message = "Something Else";
    for (int i = 0; i < 1000; i++) {
        channel.basicPublish("", queneNAme, null, message.getBytes());
    }
    System.out.println("Sent '" + message + "'");
    channel.close();
    connection.close();

}

From source file:com.DeadLetterReceiver.java

License:Open Source License

public static void main(String[] args)
        throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(HOSTNAME);//  ww w  .ja v a 2 s  . com
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    //creating reply queue
    try {
        channel.queueDeclarePassive(QUEUE_NAME);
    } catch (java.io.IOException e) {
        if (!channel.isOpen())
            channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    }

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

    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        BasicProperties props = delivery.getProperties();
        String message = new String(delivery.getBody());
        System.out.println(" [x] Response received '" + message + "'");
        System.out.println("Correlation id : " + props.getCorrelationId());
    }
}

From source file:com.DeadLetterSender.java

License:Open Source License

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

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(HOSTNAME);/*from   ww w  .  j  a  v  a  2s. c  o m*/
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    try {
        channel.exchangeDeclarePassive(EXCHANGE_NAME);
    } catch (java.io.IOException e) {
        if (!channel.isOpen())
            channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, "direct", true);
    }

    try {
        channel.queueDeclarePassive(QUEUE_NAME);
    } catch (java.io.IOException e) {
        if (!channel.isOpen())
            channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    }
    channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, QUEUE_NAME);

    // Request Message
    String message = "<soapenv:Envelope" + " xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
            + "<soapenv:Body>\n" + "  <p:greet xmlns:p=\"http://service.wso2.org\">\n" + "     <in>" + "IBM"
            + "</in>\n" + "  </p:greet>\n" + "</soapenv:Body>\n" + "</soapenv:Envelope>";

    // Adding Message Properties
    AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties().builder();
    builder.messageId("007");
    builder.contentType("text/xml");
    builder.correlationId("1111");
    builder.replyTo(REPLY_QUEUE_NAME);
    builder.contentEncoding("UTF-8");

    // Custom user properties
    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put("SOAP_ACTION", "getQuote");
    builder.headers(headers);

    // Publish the message to exchange
    channel.basicPublish(EXCHANGE_NAME, QUEUE_NAME, builder.build(), message.getBytes());
    channel.close();
    connection.close();
}

From source file:com.es.dashboard.ConnectionBroker.java

@PostConstruct
public void init() {

    bigBaite = new LinkedList<>();
    readings = new ArrayList<Reading>();
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("systembus"); // RabbitMQ IP
    Connection connection = null;
    try {//from   w  w  w  .  ja va  2 s . c om
        connection = factory.newConnection();
    } catch (IOException ex) {
        logger.error(ex);
    } catch (TimeoutException ex) {
        logger.error(ex);
    }
    Channel channel = null;
    try {
        channel = connection.createChannel();
    } catch (IOException ex) {
        logger.error(ex);
    }

    try {
        channel.exchangeDeclare("sensors", "topic"); // sensors is the name of the exchange
    } catch (IOException ex) {
        logger.error(ex);
    }
    AMQP.Queue.DeclareOk result = null;
    try {
        result = channel.queueDeclare("", false, true, false, null);
    } catch (IOException ex) {
        logger.error(ex);
    }
    String queuename = result.getQueue();
    try {
        channel.queueBind(queuename, "sensors", "realtime.sensordata"); // Binding key is #, this will consume all messages
        channel.queueBind(queuename, "sensors", "realtime.alarms"); // Binding key is #, this will consume all messages
    } catch (IOException ex) {
        logger.error(ex);
    }

    logger.info(" [*] Waiting for messages. To exit press CTRL+C");

    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");
            EventBus eventBus = EventBusFactory.getDefault().eventBus();
            Gson gson = new Gson();
            Type type = new TypeToken<Map<String, String>>() {
            }.getType();
            Map<String, String> myMap = gson.fromJson(message, type);
            if (envelope.getRoutingKey().equals("realtime.alarms")) {
                eventBus.publish("/channel", message);
                return;
            }
            logger.info(envelope.getRoutingKey());

            readings.add(new Reading(new Date(Long.parseLong(myMap.get("timestamp"))), myMap.get("data"),
                    myMap.get("name"), myMap.get("room")));
            eventBus.publish("/channel", message);

        }
    };
    try {
        //RequestContext.getCurrentInstance().execute("function rpt() {$(\".qualquer\").first().trigger(\"click\")}"
        //        + "var timeoutdummy = window.setInterval(rpt,2000);");
        channel.basicConsume(queuename, true, consumer);
    } catch (IOException ex) {
        ex.printStackTrace();
        logger.error(ex);
    }

}

From source file:com.es.dashboard.ConnectionBrokerJPA.java

@PostConstruct
public void init() {
    bigBaite = new LinkedList<>();
    readings = new ArrayList<Reading>();
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("systembus"); // RabbitMQ IP
    Connection connection = null;
    try {/*from   w w  w  . j a v  a 2  s . c o  m*/
        connection = factory.newConnection();
    } catch (IOException ex) {
        logger.error(ex);
    } catch (TimeoutException ex) {
        logger.error(ex);
    }
    Channel channel = null;
    try {
        channel = connection.createChannel();
    } catch (IOException ex) {
        logger.error(ex);
    }

    try {
        channel.exchangeDeclare("sensors", "topic"); // sensors is the name of the exchange
    } catch (IOException ex) {
        logger.error(ex);
    }
    AMQP.Queue.DeclareOk result = null;
    try {
        result = channel.queueDeclare("", false, true, false, null);
    } catch (IOException ex) {
        logger.error(ex);
    }
    String queuename = result.getQueue();
    try {
        channel.queueBind(queuename, "sensors", "dashboard.response"); // Binding key is #, this will consume all messages
    } catch (IOException ex) {
        logger.error(ex);
    }

    logger.info(" [*] Waiting for messages. To exit press CTRL+C");

    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");

            EventBus eventBus = EventBusFactory.getDefault().eventBus();
            Gson gson = new Gson();
            Type type = new TypeToken<Map<String, String>>() {
            }.getType();
            Map<String, String> myMap = gson.fromJson(message, type);
            if (envelope.getRoutingKey().equals("realtime.alarms")) {
                eventBus.publish("/jpa", message);
                return;
            }
            System.out.println(envelope.getRoutingKey());
            logger.info(envelope.getRoutingKey());

            //readings.add(new Reading(new Date(Long.parseLong(myMap.get("timestamp"))), myMap.get("value"), myMap.get("name"), myMap.get("room")));
            //System.out.println("publishing " + msg_to_publish);
            eventBus.publish("/jpa", message);
            //System.out.println("published");

        }
    };
    try {
        //RequestContext.getCurrentInstance().execute("function rpt() {$(\".qualquer\").first().trigger(\"click\")}"
        //        + "var timeoutdummy = window.setInterval(rpt,2000);");
        channel.basicConsume(queuename, true, consumer);
    } catch (IOException ex) {
        ex.printStackTrace();
        logger.error(ex);
    }

}

From source file:com.espertech.esperio.amqp.AMQPSupportReceiveRunnable.java

License:Open Source License

public void run() {
    try {/*from w  ww. j ava2 s  .  c o  m*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(hostName);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // java.lang.String queue, boolean durable, boolean exclusive, boolean autoDelete, java.util.Map<java.lang.String,java.lang.Object> arguments
        channel.queueDeclare(queueName, false, false, true, null);

        log.info("Start receiving messages");

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

        int count = 0;
        while (true) {
            final QueueingConsumer.Delivery msg = consumer.nextDelivery(waitMSecNextMsg);
            if (msg == null) {
                continue;
            }
            final byte[] bytes = msg.getBody();
            callback.handleMessage(bytes);

            if (isShutdown()) {
                break;
            }
        }

        log.info("Completed publishing messages: " + count + " messages");
    } catch (Exception ex) {
        log.error("Error attaching to AMQP: " + ex.getMessage(), ex);
    }
}

From source file:com.espertech.esperio.amqp.AMQPSupportSendRunnable.java

License:Open Source License

public void run() {
    try {/*from   w  w w.ja  v  a  2 s.c  om*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(hostName);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // java.lang.String queue, boolean durable, boolean exclusive, boolean autoDelete, java.util.Map<java.lang.String,java.lang.Object> arguments
        channel.queueDeclare(queueName, false, false, true, null);

        log.info("Start publishing messages: " + events.size() + " messages");

        int count = 0;
        while (true) {
            if (events.isEmpty()) {
                break;
            }

            Object next = events.remove(0);
            byte[] bytes = SerializerUtil.objectToByteArr(next);
            channel.basicPublish("", queueName, null, bytes);
            count++;

            log.info("Publishing message #" + count + ": " + next);
            Thread.sleep(msecSleepTime);

            if (isShutdown()) {
                break;
            }
        }

        log.info("Completed publishing messages: " + count + " messages");
    } catch (Exception ex) {
        log.error("Error attaching to AMQP: " + ex.getMessage(), ex);
    }
}

From source file:com.espertech.esperio.amqp.AMQPSupportUtil.java

License:Open Source License

public static int drainQueue(String hostName, String queueName) {
    Connection connection = null;
    Channel channel = null;

    try {//from  w ww  .j  a  va2 s .  c o m
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(hostName);
        connection = factory.newConnection();
        channel = connection.createChannel();

        // java.lang.String queue, boolean durable, boolean exclusive, boolean autoDelete, java.util.Map<java.lang.String,java.lang.Object> arguments
        channel.queueDeclare(queueName, false, false, true, null);

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

        int count = 0;
        while (true) {
            final QueueingConsumer.Delivery msg = consumer.nextDelivery(1);
            if (msg == null) {
                return count;
            }
        }
    } catch (Exception ex) {
        log.error("Error attaching to AMQP: " + ex.getMessage(), ex);
    } finally {
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return -1;
}

From source file:com.eventbook.controller.SpringbootPocController.java

@RequestMapping(value = "/rabbitMQSendTest", method = RequestMethod.GET)
public String rabbitMQSendTest(@RequestParam(value = "message", defaultValue = "Hello World!") String message) {
    try {/*from www.j  a va  2 s  .co m*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("rabbitmq");
        factory.setPort(5672);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
        System.out.println(" [x] Sent '" + message + "'");

        channel.close();
        connection.close();

        return "rabbitMQSendTest Sent: " + message;
    } catch (IOException | TimeoutException ex) {
        Logger.getLogger(SpringbootPocController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return "rabbitMQSendTest has been failed!!!";
}

From source file:com.eventbook.controller.SpringbootPocController.java

@RequestMapping(value = "/rabbitMQReceiveTest", method = RequestMethod.GET)
public String rabbitMQReceiveTest() {
    try {//from   w w w  . j a v a  2s .c  o m
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("rabbitmq");
        factory.setPort(5672);
        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");
        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 + "'");
            }
        };
        channel.basicConsume(QUEUE_NAME, true, consumer);

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

    return "Getting messages from RabbitMQ!!";
}