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:org.springframework.integration.amqp.config.EchoSample.java

License:Apache License

@BeforeClass
public static void setup() {
    SingleConnectionFactory connectionFactory = new SingleConnectionFactory();
    connectionFactory.setUsername("guest");
    connectionFactory.setPassword("guest");
    RabbitTemplate template = new RabbitTemplate(connectionFactory);
    template.execute(new ChannelCallback<Object>() {
        @Override/*www . j av  a2s  . c o m*/
        public Object doInRabbit(Channel channel) throws Exception {
            channel.queueDeclare("si.test.queue", true, false, false, null);
            channel.exchangeDeclare("si.test.exchange", "direct", true);
            channel.queueBind("si.test.queue", "si.test.exchange", "si.test.binding");
            return null;
        }
    });
}

From source file:org.teksme.server.common.messaging.AMQPBrokerManager.java

License:Apache License

protected void declareQueueing(Connection conn, MessageMiddleware config) throws IOException {

    String routingKey = null;/*from w w  w.  j  a  v  a  2  s .com*/
    String exchangeName = null;
    String queueName = null;
    String type = null;
    boolean durable = false;
    boolean autoDelete = false;
    boolean exclusive = false;

    List<MessageMiddleware.Queue> queues = config.getQueues();
    for (Queue queue : queues) {
        queueName = queue.getName();
        routingKey = queue.getKey();
        exchangeName = queue.getExchange();
        type = queue.getType();
        durable = queue.isDurable();
        autoDelete = queue.isAutoDelete();
        exclusive = queue.isExclusive();

        logger.info("Declaring exchange [" + exchangeName + "] and queue [" + queueName + "]");

        Channel channel = conn.createChannel();

        channel.exchangeDeclare(exchangeName, type, durable);
        channel.queueDeclare(queueName, durable, exclusive, autoDelete, null);

        logger.info("Binding queue [" + queueName + "] and exchange [" + exchangeName + "] to routing key ["
                + routingKey + "]");
        channel.queueBind(queueName, exchangeName, routingKey);

    }

}

From source file:org.thingsboard.server.extensions.rabbitmq.DemoClient.java

License:Apache License

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

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(HOST);/*from  w  ww  .  j  a  va2 s .  c  o m*/
    factory.setUsername(USERNAME);
    factory.setPassword(PASSWORD);

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

    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    System.out.println(" [*] Waiting for messages.");
    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);

}

From source file:org.voltdb.bulkloader.RMQCSVReceive.java

License:Open Source License

public static void receiveMessages(RMQOptions rmqOpts, TestOptions testOpts, String[] args) throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(rmqOpts.host);//from ww  w.  ja  v a2 s.c  om
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    if (rmqOpts.exchange != null) {
        if (rmqOpts.extype != null) {
            channel.exchangeDeclare(rmqOpts.exchange, rmqOpts.extype);
        }
        for (String bindingKey : rmqOpts.bindings) {
            channel.queueBind(rmqOpts.queue, rmqOpts.exchange, bindingKey);
        }
    }

    try {
        channel.queueDeclare(rmqOpts.queue, rmqOpts.persistent, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
        channel.basicQos(1);
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(rmqOpts.queue, false, consumer);
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            // Sleep 1 second for every trailing '.'.
            int dotCount = 0;
            for (int i = message.length() - 1; i >= 0; --i) {
                if (message.charAt(i) == '.') {
                    dotCount++;
                } else {
                    break;
                }
            }
            if (dotCount > 0) {
                message = message.substring(0, message.length() - dotCount);
            }
            System.out.printf(" [x] Received '%s'\n", message);
            Thread.sleep(dotCount * 1000);
        }
    } catch (ShutdownSignalException | ConsumerCancelledException | InterruptedException e) {
        e.printStackTrace();
    } finally {
        channel.close();
        connection.close();
    }
}

From source file:org.voltdb.bulkloader.RMQCSVSend.java

License:Open Source License

private static void sendMessages(RMQOptions rmqOpts, RandomSleeper.RSOptions sleeperOpts, TestOptions testOpts)
        throws InterruptedException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(rmqOpts.host);//from   ww  w. ja v  a2  s  .co m

    Connection connection = null;
    Channel channel = null;
    String exchangeName = "";
    // Use the queue name if the routing key is not specified.
    String routingKey = rmqOpts.routing != null ? rmqOpts.routing : rmqOpts.queue;
    try {
        connection = factory.newConnection();
        channel = connection.createChannel();
        if (rmqOpts.exchange != null) {
            exchangeName = rmqOpts.exchange;
            channel.exchangeDeclare(exchangeName, rmqOpts.extype);
        }
    } catch (IOException e1) {
        e1.printStackTrace();
        System.exit(255);
    }

    try {
        channel.queueDeclare(rmqOpts.queue, rmqOpts.persistent, false, false, null);
        try {
            while (testOpts.lineIter.hasNext()) {
                String message = testOpts.lineIter.next();
                channel.basicPublish(exchangeName, routingKey, MessageProperties.TEXT_PLAIN,
                        message.getBytes());
                System.out.printf(" [x] Sent '%s'\n", message);
                sleeperOpts.sleeper.sleep();
            }
        } finally {
            testOpts.lineIter.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            channel.close();
            connection.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.wildfly.connector.rabbitmq.ConnectorTestCase.java

License:Open Source License

@Test
public void testConnectionFactory() throws Exception {
    Assert.assertNotNull(connectionFactory1);
    Assert.assertNotNull(queue);/*from   w w w  .j a v  a2s  . c om*/

    RabbitmqConnection connection = connectionFactory1.getConnection();
    Assert.assertNotNull(connection);
    String queueName = "testing";
    Channel channel = connection.createChannel();
    channel.queueDeclare(queueName, false, false, false, null);
    String message = "Hello World!";

    final CountDownLatch counter = new CountDownLatch(1);
    Consumer consume = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties,
                byte[] body) throws IOException {
            Assert.assertEquals("Hello World!", new String(body));
            counter.countDown();
        }
    };

    channel.basicConsume(queueName, true, consume);
    channel.basicPublish("", queueName, null, message.getBytes());
    counter.await(10, TimeUnit.SECONDS);
    Assert.assertEquals(0, counter.getCount());
    channel.close();

}

From source file:org.wso2.carbon.event.adapter.rabbitmq.internal.util.RabbitMQEventAdapterUtils.java

License:Open Source License

/**
 * @param connection   Connection to the RabbitMQ
 * @param queueName    Name of the queue
 * @param isDurable    Whether durable or not
 * @param isExclusive  Whether exclusive or not
 * @param isAutoDelete Whether queue is auto delete or not
 * @throws IOException//  w  w w  .j a v  a  2s  .co  m
 */
public static void declareQueue(Connection connection, String queueName, String isDurable, String isExclusive,
        String isAutoDelete) throws IOException {

    boolean queueAvailable = isQueueAvailable(connection, queueName);
    Channel channel = connection.createChannel();
    if (!queueAvailable) {
        if (log.isDebugEnabled()) {
            log.debug("Queue :" + queueName + " not found or already declared exclusive. Declaring the queue.");
        }
        // Declare the named queue if it does not exists.
        if (!channel.isOpen()) {
            channel = connection.createChannel();
            log.debug("Channel is not open. Creating a new channel.");
        }
        try {
            channel.queueDeclare(queueName, isDurableQueue(isDurable), isExclusiveQueue(isExclusive),
                    isAutoDeleteQueue(isAutoDelete), null);
        } catch (IOException e) {
            handleException("Error while creating queue: " + queueName, e);
        }
    }
}

From source file:org.wso2.carbon.event.adaptor.rabbitmq.output.RabbitMQOutputEventAdaptorType.java

License:Open Source License

/**
 * <pre>/*from ww  w. j  av a2  s. co m*/
 * publish
 * <pre>
 * 
 * @param outputEventAdaptorMessageConfiguration
 * @param message
 * @param outputEventAdaptorConfiguration
 * @param tenantId
 * @see org.wso2.carbon.event.output.adaptor.core.AbstractOutputEventAdaptor#publish(org.wso2.carbon.event.output.adaptor.core.message.config.OutputEventAdaptorMessageConfiguration, java.lang.Object, org.wso2.carbon.event.output.adaptor.core.config.OutputEventAdaptorConfiguration, int)
 */
@Override
protected void publish(OutputEventAdaptorMessageConfiguration outputEventAdaptorMessageConfiguration,
        Object message, OutputEventAdaptorConfiguration outputEventAdaptorConfiguration, int tenantId) {

    LOGGER.debug("*** DEBUG RabbitMQOutputEventAdaptorType.publish()");

    try {
        Channel channel = getChannel(outputEventAdaptorConfiguration, tenantId);

        String queue = outputEventAdaptorMessageConfiguration.getOutputMessageProperties()
                .get(RabbitMQEventAdaptorConstants.ADAPTOR_RABBITMQ_QUEUE);

        boolean isExist = false;
        try {
            channel.queueDeclarePassive(queue);
            isExist = true;
        } catch (IOException e) {
            LOGGER.info("*** INFO : [" + queue + "] does not exist.");
        }

        if (!isExist) {
            String dlmExchangeName = "exchange_dlm";
            String routingKey = queue;

            if (!channel.isOpen()) {
                channel = getChannel(outputEventAdaptorConfiguration, tenantId);
            }

            /**
             *  Add configuration for DLM
             */
            Map<String, Object> arg = new HashMap<String, Object>();
            arg.put("x-dead-letter-exchange", dlmExchangeName);
            arg.put("x-dead-letter-routing-key", routingKey);

            /**
             *  Create a queue and binding with DLM
             */
            channel.queueDeclare(queue, true, false, false, arg);
            channel.queueBind(queue, dlmExchangeName, routingKey);
        }

        if (message instanceof String) {
            channel.basicPublish("", queue, MessageProperties.PERSISTENT_TEXT_PLAIN,
                    ((String) message).getBytes());
        } else {
            channel.basicPublish("", queue, MessageProperties.PERSISTENT_TEXT_PLAIN,
                    message.toString().getBytes());
        }
        LOGGER.debug("*** DEBUG: [x] Sent " + message.getClass() + " type, '" + message + "'");
    } catch (IOException e) {
        throw new AdaptorRuntimeException(e);
    }
}

From source file:org.wso2.carbon.inbound.endpoint.protocol.rabbitmq.RabbitMQUtils.java

License:Open Source License

/**
 *
 * @param connection/*from  w  w  w.j ava 2  s.  c o  m*/
 * @param queueName
 * @param isDurable
 * @param isExclusive
 * @param isAutoDelete
 * @throws IOException
 */
public static void declareQueue(Connection connection, String queueName, boolean isDurable, boolean isExclusive,
        boolean isAutoDelete) throws IOException {

    boolean queueAvailable = isQueueAvailable(connection, queueName);
    Channel channel = connection.createChannel();

    if (!queueAvailable) {
        if (log.isDebugEnabled()) {
            log.debug("Queue :" + queueName + " not found or already declared exclusive. Declaring the queue.");
        }
        // Declare the named queue if it does not exists.
        if (!channel.isOpen()) {
            channel = connection.createChannel();
            log.debug("Channel is not open. Creating a new channel.");
        }
        try {
            channel.queueDeclare(queueName, isDurable, isExclusive, isAutoDelete, null);
        } catch (IOException e) {
            handleException("Error while creating queue: " + queueName, e);
        }
    }
}

From source file:org.wso2.carbon.inbound.endpoint.protocol.rabbitmq.RabbitMQUtils.java

License:Open Source License

public static void declareQueue(Connection connection, String queueName, Hashtable<String, String> properties)
        throws IOException {
    Boolean queueAvailable = isQueueAvailable(connection, queueName);
    Channel channel = connection.createChannel();

    if (!queueAvailable) {
        // Declare the named queue if it does not exists.
        if (!channel.isOpen()) {
            channel = connection.createChannel();
            log.debug("Channel is not open. Creating a new channel.");
        }/*from   w w w.  ja v a2  s  .  c o  m*/
        try {
            channel.queueDeclare(queueName, isDurableQueue(properties), isExclusiveQueue(properties),
                    isAutoDeleteQueue(properties), null);

        } catch (IOException e) {
            handleException("Error while creating queue: " + queueName, e);
        }
    }
}