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: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  ww.ja 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:uk.ac.sanger.cgp.wwdocker.messages.Messaging.java

License:Open Source License

/**
 * Gets all the messages in a queue, best for queues which receive status updates.
 * @param queue//from  www.j  a v a  2s.c  om
 * @param wait
 * @return List of JSON strings representing objects, you need to know what type of object the queue will return and handle this outside of here
 * @throws IOException
 * @throws InterruptedException 
 */
public List<String> getMessageStrings(String queue, long wait) throws IOException, InterruptedException {
    List<String> responses = new ArrayList();
    Connection connectionRcv = getRmqConn();
    Channel channel = connectionRcv.createChannel();
    channel.queueDeclare(queue, true, false, false, null);
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue, true, consumer);
    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery(wait);
        if (delivery == null) {
            break;
        }
        String message = new String(delivery.getBody());
        logger.info(queue + " recieved: " + message);
        responses.add(message);
    }
    channel.close();
    closeRmqConn(connectionRcv);
    return responses;
}

From source file:uk.ac.soton.itinnovation.experimedia.arch.ecc.amqpAPI.impl.faces.AbstractAMQPInterface.java

protected void createQueue() {
    assignBindings();/*  w w w.  j  a  va  2s .  c o m*/

    String targetExchange = actingAsProvider ? providerExchangeName : userExchangeName;
    String targetRouteKey = actingAsProvider ? providerRoutingKey : userRoutingKey;

    try {
        Channel channel = (Channel) amqpChannel.getChannelImpl();

        channel.queueDeclare(subListenQueue, false, // Durable
                false, // Exclusive
                true, // Auto-delete
                null); // Args

        channel.queueBind(subListenQueue, targetExchange, targetRouteKey); // Args
    } catch (IOException ioe) {
        amqpIntLogger.error("Could not create AMQP queue: " + ioe.getMessage());
    }

}

From source file:user.Client.java

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("rabbitmq.akhfa.me");
    factory.setUsername(username);/*  w w  w .  j  a  v a  2  s .c om*/
    factory.setPassword(password);
    factory.setVirtualHost("pat");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    ArrayList<String> daftarNick = getAllQueues();

    String nick = "";

    while (true) {
        Scanner in = new Scanner(System.in);

        System.out.print("Please enter your command: ");
        String command = in.nextLine();

        String[] com = command.split(" ", 2);
        try {
            switch (com[0]) {
            case "/NICK":
                if (!nick.equals("")) {
                    System.out.println("You have registered with nickname: " + nick);
                } else {
                    if (!daftarNick.contains(com[1])) {
                        channel.queueDeclare(com[1], false, false, true, null);
                        nick = com[1];
                        System.out.println("Your nickname is " + nick);

                        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");
                                filterChannel(message);
                            }
                        };
                        channel.basicConsume(nick, true, consumer);
                    } else {
                        System.out.println("Nickname exists.");
                    }
                }
                break;
            case "/JOIN":
                channel.exchangeDeclare(com[1], "fanout", false, false, false, null);
                channel.queueBind(nick, com[1], "");
                System.out.println("You have successfully join " + com[1]);
                break;
            case "/LEAVE":
                channel.queueUnbind(nick, com[1], "");
                System.out.println("Leave " + com[1]);
                break;
            case "/EXIT":
                System.out.println("bye bye...  :D");
                System.exit(0);
            default:
                String message = nick + ' ' + command;
                channel.basicPublish(com[0].substring(1), "", null, message.getBytes("UTF-8"));
                break;
            }
        } catch (Exception e) {
            if (command.compareTo("/NICK") == 0) {
                //random nick
                String random;

                if (!nick.equals("")) {
                    System.out.println("You have registered with nickname: " + nick);
                } else {
                    do {
                        random = randomNick();
                    } while (daftarNick.contains(random));

                    nick = random;

                    channel.queueDeclare(random, false, false, true, null);
                    System.out.println("Your nickname is " + random);

                    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");
                            filterChannel(message);
                        }
                    };
                    channel.basicConsume(nick, true, consumer);
                }

            } else if ((command.compareTo("/JOIN") == 0) || (command.compareTo("/LEAVE") == 0)) {
                //error
                System.out.println("Please enter channel name!");
            } else if (command.charAt(0) == '@') {
                System.out.println("Please enter your command for the channel.");
            } else {
                System.out.println("Invalid command.");
            }
        }
    }
}

From source file:util.ExampleSocialMediaStormDeclarator.java

/**
 * Main RabbitMQ declaration method. Will use RabbitMQ channel reference.
 *
 * Rabbit MQ Channel API://w w  w.  j  a v  a 2  s.c o m
 * https://www.rabbitmq.com/releases/rabbitmq-java-client/v3.1.5/rabbitmq-
 * java-client-javadoc-3.1.5/ (search for "Channel")
 *
 * @param channel
 *            rabbitmq channel
 */
@Override
public void execute(Channel channel) {
    try {
        // Storm any possible arguments that could be passed
        Map<String, Object> args = new HashMap<>();

        /*
         * Declare the queue
         *
         * API:
         * http://www.rabbitmq.com/releases/rabbitmq-java-client/v1.7.0/
         * rabbitmq-java-client-javadoc-1.7.0/com/rabbitmq/client/Channel.
         * html#queueDeclare(java.lang.String, boolean, boolean, boolean,
         * boolean, java.util.Map))
         * 
         */
        channel.queueDeclare(this.strQueueName, true, false, false, args);

        /*
         * Declare the exchange
         *
         * API:
         * http://www.rabbitmq.com/releases/rabbitmq-java-client/v1.7.0/
         * rabbitmq-java-client-javadoc-1.7.0/com/rabbitmq/client/Channel.
         * html#exchangeDeclare(java.lang.String, java.lang.String, boolean)
         */
        channel.exchangeDeclare(this.strExchange, this.strExchangeType, this.boolPersistence);

        /*
         * Bind the queue
         *
         * API:
         * http://www.rabbitmq.com/releases/rabbitmq-java-client/v1.7.0/
         * rabbitmq-java-client-javadoc-1.7.0/com/rabbitmq/client/Channel.
         * html#queueBind(java.lang.String, java.lang.String,
         * java.lang.String)
         */
        channel.queueBind(this.strQueueName, this.strExchange, this.strRoutingKey);

        // Handle Exception and allow to continue
    } catch (Exception e) {
        System.err.println("Failed to execute RabbitMQ declarations. Details: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:vn.com.uet.performance.rabbitmq.MulticastParams.java

License:Open Source License

public String configureQueue(Connection connection, String id) throws IOException {
    Channel channel = connection.createChannel();
    if (!predeclared || !exchangeExists(connection, exchangeName)) {
        channel.exchangeDeclare(exchangeName, exchangeType);
    }/*from  w  w  w  . j  a  v  a2  s . c om*/
    String qName = queueName;
    if (!predeclared || !queueExists(connection, queueName)) {
        qName = channel.queueDeclare(queueName, flags.contains("persistent"), false, autoDelete, null)
                .getQueue();
    }
    channel.queueBind(qName, exchangeName, id);
    channel.abort();
    return qName;
}

From source file:wiki.messaging.NewTask.java

License:Open Source License

public static void main(String[] args) throws IOException {
    int n = 500;/*from  w w  w  .  j a va 2s.c o  m*/
    String url = null;
    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("n")) {
            n = Integer.valueOf(args[i + 1]);
        }
    }
    DbConnector ds = new DbConnector(url);

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

    RandomDocGetter rdg = new RandomDocGetter(ds);
    for (int i = 0; i < n; i++) {
        String message = getMessage(rdg);
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
        System.out.println(" [x] Sent '" + message + "'");
    }

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

From source file:wiki.messaging.Receive.java

License:Open Source License

public static void main(String[] args) throws IOException, InterruptedException {
    String url = null;// w w w  .ja v a  2  s.c o  m
    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 w w  w.j ava  2s  .c om*/
    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();
}

From source file:wiki.messaging.Treeceive.java

License:Open Source License

public static void main(String[] args) throws IOException, InterruptedException {
    String url = null;/*from  w  ww.  j  av a  2  s .  c  o m*/
    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);
        saveResults(channel);
        System.out.println(" [x] Done");
        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }
}