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.wakkir.rabbitmq.basic.Sender.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);
    String message = "Hello World!";
    channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
    System.out.println(" [x] Sent '" + message + "'");

    channel.close();//from  ww  w. j  av  a2  s .c o m
    connection.close();
}

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  w w  . ja v a 2 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.zero_x_baadf00d.play.module.rabbitmq.RabbitMQModuleImpl.java

License:Open Source License

@Override
public Channel getChannel(final String queueName) throws IOException {
    if (this.rabbitConnection == null) {
        return null;
    }/*w w  w .java2  s. c  o m*/
    final Channel channel = this.rabbitConnection.createChannel();
    final String key = "rabbitmq.channels." + queueName.replace(" ", "_") + ".";
    channel.queueDeclare(queueName,
            !this.configuration.hasPath(key + "durable") || this.configuration.getBoolean(key + "durable"),
            this.configuration.hasPath(key + "exclusive") && this.configuration.getBoolean(key + "exclusive"),
            this.configuration.hasPath(key + "autoDelete") && this.configuration.getBoolean(key + "autoDelete"),
            null);
    return channel;
}

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

License:Open Source License

public static Channel openChannel(String queueName) {
    ConnectionFactory factory = new ConnectionFactory();

    Channel channel;
    try {// ww  w .  j  a  v  a2  s . com
        factory.setHost("45.63.124.106");
        Connection connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(queueName, false, false, false, null);
        return channel;
    } catch (IOException e) {
        e.printStackTrace();
    } catch (TimeoutException e) {
        e.printStackTrace();
    }
    return null;

}

From source file:controllers.TargetController.java

License:Open Source License

/**
 * This method pushes a message onto a RabbitMQ queue for given target
 * using global settings from project configuration file.
 *
 * @param target The field URL of the target
 * @return/*from   w w  w. j ava 2  s  .com*/
 */
public static Result archive(Long id) {

    Target target = Target.findById(id);
    Logger.debug("archiveTarget() " + target);
    if (target != null) {
        if (!target.isInScopeAllOrInheritedWithoutLicense()) {
            return ok(infomessage.render("On-demand archiving is only supported for NPLD targets."));
        }

        // Send the message:
        try {
            String queueHost = Play.application().configuration().getString(Const.QUEUE_HOST);
            String queuePort = Play.application().configuration().getString(Const.QUEUE_PORT);
            String queueName = Play.application().configuration().getString(Const.QUEUE_NAME);
            String routingKey = Play.application().configuration().getString(Const.ROUTING_KEY);
            String exchangeName = Play.application().configuration().getString(Const.EXCHANGE_NAME);

            Logger.debug("archiveTarget() queue host: " + queueHost);
            Logger.debug("archiveTarget() queue port: " + queuePort);
            Logger.debug("archiveTarget() queue name: " + queueName);
            Logger.debug("archiveTarget() routing key: " + routingKey);
            Logger.debug("archiveTarget() exchange name: " + exchangeName);

            JsonNode jsonData = Json.toJson(target);
            String message = jsonData.toString();
            Logger.debug("Crawl Now message: " + message);

            ConnectionFactory factory = new ConnectionFactory();
            if (queueHost != null) {
                factory.setHost(queueHost);
            }
            if (queuePort != null) {
                factory.setPort(Integer.parseInt(queuePort));
            }
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();

            channel.exchangeDeclare(exchangeName, "direct", true);
            channel.queueDeclare(queueName, true, false, false, null);
            channel.queueBind(queueName, exchangeName, routingKey);

            BasicProperties.Builder propsBuilder = new BasicProperties.Builder();
            propsBuilder.deliveryMode(2);
            channel.basicPublish(exchangeName, routingKey, propsBuilder.build(), message.getBytes());

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

        } catch (IOException e) {
            String msg = "There was a problem queuing this crawl instruction. Please refer to the system administrator.";
            User currentUser = User.findByEmail(request().username());
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            String msgFullTrace = sw.toString();
            Logger.error(msgFullTrace);
            if (currentUser.hasRole("sys_admin")) {
                msg = msgFullTrace;
            }
            return ok(infomessage.render(msg));
        } catch (Exception e) {
            String msg = "There was a problem queuing this crawl instruction. Please refer to the system administrator.";
            User currentUser = User.findByEmail(request().username());
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            String msgFullTrace = sw.toString();
            Logger.error(msgFullTrace);
            if (currentUser.hasRole("sys_admin")) {
                msg = msgFullTrace;
            }
            return ok(infomessage.render(msg));
        }
    } else {
        Logger.debug("There was a problem sending the message. Target field for archiving is empty");
        return ok(infomessage
                .render("There was a problem sending the message. Target field for archiving is empty"));
    }
    return ok(ukwalicenceresult.render());
}

From source file:coyote.mq.AbstractMessagingTest.java

License:Open Source License

public void sendMessage(String queueName, DataFrame message) {
    if (StringUtil.isNotBlank(queueName) && message != null) {
        byte[] data = message.getBytes();
        try {//from ww  w .j ava2s .c  o  m
            ConnectionFactory factory = new ConnectionFactory();
            factory.setUri(broker.getBrokerUri());
            factory.useSslProtocol();
            // username:password should be in the URI for our tests
            try (Connection connection = factory.newConnection()) {
                Channel channel = connection.createChannel();
                channel.queueDeclare(queueName, false, false, false, null);
                channel.basicPublish("", queueName, null, data);
                Log.debug("Sent " + data.length + " bytes to '" + queueName + "'");
            }
        } catch (Exception e) {
            Log.error("Could not send message: " + e.getClass().getSimpleName() + "-" + e.getMessage());
        }
    }
}

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  w  w  .j  ava  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:deck36.storm.plan9.RabbitMQDeclarator.java

License:Open Source License

@Override
public void execute(Channel channel) {

    try {//from   ww  w  .  ja  va 2 s  .c o m

        channel.exchangeDeclare(exchange, // name
                "topic", // type
                true // durable?
        );

        channel.queueDeclare(queue, // name
                true, // durable?
                false, // exclusive?
                false, // autoDelete
                null // Map(<String, Object> arguments
        );

        channel.queueBind(queue, exchange, routingKey);

    } catch (IOException e) {
        throw new RuntimeException("Error executing rabbitmq declarations.", e);
    }
}

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

License:Open Source License

public static void main(String[] argv) {
    Channel channel = null;
    try {/* w ww  .j  a v  a2s.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 {/* ww  w.ja v  a 2  s  .  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) {
            }
        }
    }
}