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:info.pancancer.arch3.utils.Utilities.java

License:Open Source License

public static String setupQueueOnExchange(Channel channel, String queue, String suffix) throws IOException {
    try {/*from w w  w  .j av  a 2 s. c o  m*/
        return channel.queueDeclare(queue + "_for_" + suffix, true, false, false, null).getQueue();
    } catch (IOException ex) {
        LOG.error("Error setting up queue on exchange: " + ex.getMessage(), ex);
        throw ex;
    }
}

From source file:io.bootique.rabbitmq.client.channel.QueueConfig.java

License:Apache License

public void queueDeclare(Channel channel, String queueName) throws IOException {
    channel.queueDeclare(queueName, durable, exclusive, autoDelete, arguments);
}

From source file:io.druid.firehose.rabbitmq.RabbitMQFirehoseFactory.java

License:Apache License

@Override
public Firehose connect(StringInputRowParser firehoseParser) throws IOException {
    final StringInputRowParser stringParser = firehoseParser;

    ConnectionOptions lyraOptions = new ConnectionOptions(this.connectionFactory);
    Config lyraConfig = new Config().withRecoveryPolicy(new RetryPolicy().withMaxRetries(config.getMaxRetries())
            .withRetryInterval(Duration.seconds(config.getRetryIntervalSeconds()))
            .withMaxDuration(Duration.seconds(config.getMaxDurationSeconds())));

    String queue = config.getQueue();
    String exchange = config.getExchange();
    String routingKey = config.getRoutingKey();

    boolean durable = config.isDurable();
    boolean exclusive = config.isExclusive();
    boolean autoDelete = config.isAutoDelete();

    final Connection connection = Connections.create(lyraOptions, lyraConfig);

    connection.addShutdownListener(new ShutdownListener() {
        @Override/*ww  w  .  j  av  a2  s.co  m*/
        public void shutdownCompleted(ShutdownSignalException cause) {
            log.warn(cause, "Connection closed!");
        }
    });

    final Channel channel = connection.createChannel();
    channel.queueDeclare(queue, durable, exclusive, autoDelete, null);
    channel.queueBind(queue, exchange, routingKey);
    channel.addShutdownListener(new ShutdownListener() {
        @Override
        public void shutdownCompleted(ShutdownSignalException cause) {
            log.warn(cause, "Channel closed!");
        }
    });

    // We create a QueueingConsumer that will not auto-acknowledge messages since that
    // happens on commit().
    final QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue, false, consumer);

    return new Firehose() {
        /**
         * Storing the latest delivery as a member variable should be safe since this will only be run
         * by a single thread.
         */
        private Delivery delivery;

        /**
         * Store the latest delivery tag to be able to commit (acknowledge) the message delivery up to
         * and including this tag. See commit() for more detail.
         */
        private long lastDeliveryTag;

        @Override
        public boolean hasMore() {
            delivery = null;
            try {
                // Wait for the next delivery. This will block until something is available.
                delivery = consumer.nextDelivery();
                if (delivery != null) {
                    lastDeliveryTag = delivery.getEnvelope().getDeliveryTag();
                    // If delivery is non-null, we report that there is something more to process.
                    return true;
                }
            } catch (InterruptedException e) {
                // A little unclear on how we should handle this.

                // At any rate, we're in an unknown state now so let's log something and return false.
                log.wtf(e, "Got interrupted while waiting for next delivery. Doubt this should ever happen.");
            }

            // This means that delivery is null or we caught the exception above so we report that we have
            // nothing more to process.
            return false;
        }

        @Override
        public InputRow nextRow() {
            if (delivery == null) {
                //Just making sure.
                log.wtf("I have nothing in delivery. Method hasMore() should have returned false.");
                return null;
            }

            return stringParser.parse(StringUtils.fromUtf8(delivery.getBody()));
        }

        @Override
        public Runnable commit() {
            // This method will be called from the same thread that calls the other methods of
            // this Firehose. However, the returned Runnable will be called by a different thread.
            //
            // It should be (thread) safe to copy the lastDeliveryTag like we do below and then
            // acknowledge values up to and including that value.
            return new Runnable() {
                // Store (copy) the last delivery tag to "become" thread safe.
                final long deliveryTag = lastDeliveryTag;

                @Override
                public void run() {
                    try {
                        log.info("Acknowledging delivery of messages up to tag: " + deliveryTag);

                        // Acknowledge all messages up to and including the stored delivery tag.
                        channel.basicAck(deliveryTag, true);
                    } catch (IOException e) {
                        log.error(e, "Unable to acknowledge message reception to message queue.");
                    }
                }
            };
        }

        @Override
        public void close() throws IOException {
            log.info("Closing connection to RabbitMQ");
            channel.close();
            connection.close();
        }
    };
}

From source file:io.druid.segment.realtime.firehose.RabbitMQFirehoseFactory.java

License:Open Source License

@Override
public Firehose connect() throws IOException {
    String queue = config.getQueue();
    String exchange = config.getExchange();
    String routingKey = config.getRoutingKey();

    boolean durable = config.isDurable();
    boolean exclusive = config.isExclusive();
    boolean autoDelete = config.isAutoDelete();

    final Connection connection = connectionFactory.newConnection();
    connection.addShutdownListener(new ShutdownListener() {
        @Override//from   w  w w. j  a  v  a2 s.  com
        public void shutdownCompleted(ShutdownSignalException cause) {
            log.warn(cause, "Connection closed!");
            //FUTURE: we could try to re-establish the connection here. Not done in this version though.
        }
    });

    final Channel channel = connection.createChannel();
    channel.queueDeclare(queue, durable, exclusive, autoDelete, null);
    channel.queueBind(queue, exchange, routingKey);
    channel.addShutdownListener(new ShutdownListener() {
        @Override
        public void shutdownCompleted(ShutdownSignalException cause) {
            log.warn(cause, "Channel closed!");
            //FUTURE: we could try to re-establish the connection here. Not done in this version though.
        }
    });

    // We create a QueueingConsumer that will not auto-acknowledge messages since that
    // happens on commit().
    final QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue, false, consumer);

    return new Firehose() {
        /**
         * Storing the latest delivery as a member variable should be safe since this will only be run
         * by a single thread.
         */
        private QueueingConsumer.Delivery delivery;

        /**
         * Store the latest delivery tag to be able to commit (acknowledge) the message delivery up to
         * and including this tag. See commit() for more detail.
         */
        private long lastDeliveryTag;

        @Override
        public boolean hasMore() {
            delivery = null;
            try {
                // Wait for the next delivery. This will block until something is available.
                delivery = consumer.nextDelivery();
                if (delivery != null) {
                    lastDeliveryTag = delivery.getEnvelope().getDeliveryTag();
                    // If delivery is non-null, we report that there is something more to process.
                    return true;
                }
            } catch (InterruptedException e) {
                // A little unclear on how we should handle this.

                // At any rate, we're in an unknown state now so let's log something and return false.
                log.wtf(e, "Got interrupted while waiting for next delivery. Doubt this should ever happen.");
            }

            // This means that delivery is null or we caught the exception above so we report that we have
            // nothing more to process.
            return false;
        }

        @Override
        public InputRow nextRow() {
            if (delivery == null) {
                //Just making sure.
                log.wtf("I have nothing in delivery. Method hasMore() should have returned false.");
                return null;
            }

            return parser.parse(new String(delivery.getBody()));
        }

        @Override
        public Runnable commit() {
            // This method will be called from the same thread that calls the other methods of
            // this Firehose. However, the returned Runnable will be called by a different thread.
            //
            // It should be (thread) safe to copy the lastDeliveryTag like we do below and then
            // acknowledge values up to and including that value.
            return new Runnable() {
                // Store (copy) the last delivery tag to "become" thread safe.
                final long deliveryTag = lastDeliveryTag;

                @Override
                public void run() {
                    try {
                        log.info("Acknowledging delivery of messages up to tag: " + deliveryTag);

                        // Acknowledge all messages up to and including the stored delivery tag.
                        channel.basicAck(deliveryTag, true);
                    } catch (IOException e) {
                        log.error(e, "Unable to acknowledge message reception to message queue.");
                    }
                }
            };
        }

        @Override
        public void close() throws IOException {
            log.info("Closing connection to RabbitMQ");
            channel.close();
            connection.close();
        }
    };
}

From source file:io.qdb.server.input.RabbitMQInputHandler.java

License:Apache License

protected void initChannel(Channel channel) throws IOException {
    channel.queueDeclare(queue, queueDurable, false, false, null);
    if (exchange != null) {
        channel.exchangeDeclare(exchange, exchangeType, exchangeDurable);
        channel.queueBind(queue, exchange, routingKey);
    }/*from  w w w  . ja  v a 2 s.c o  m*/
}

From source file:io.qdb.server.output.RabbitMQOutputHandler.java

License:Apache License

protected void initChannel(Channel channel) throws IOException {
    channel.exchangeDeclare(exchange, exchangeType, exchangeDurable);
    if (queues != null) {
        for (int i = 0; i < queues.length; i++) {
            String q = queues[i];
            channel.queueDeclare(q, queueDurable[i], false, false, null);
            channel.queueBind(q, exchange, "");
        }/*from  www  .j a  va2s.co  m*/
    }
}

From source file:io.snappydata.rabbitmq.RabbitMQPublisher.java

License:Open Source License

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, true, false, false, null);

    int logCount = 0;
    int totalNumLogs = 1000000;

    while (logCount <= totalNumLogs) {
        AdImpressionLog log = AdImpressionGenerator.nextRandomAdImpression();
        channel.basicPublish("", QUEUE_NAME, null, getLogBytes(log));
        logCount += 1;//from w ww  .j a  v a  2 s . co  m
        if (logCount % 100000 == 0) {
            System.out.println("RabbitMQPublisher published total " + logCount + " messages");
        }
    }

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

From source file:it.av.fac.messaging.rabbitmq.RabbitMQChannelPool.java

public static synchronized Channel createChannel(Connection conn, String queueIn, String queueOut,
        String routingKeyIn, String routingKeyOut) throws IOException {
    String UID = obtainUniqueId(queueIn, queueOut, routingKeyIn, routingKeyOut);

    if (!POOL.containsKey(UID) || !POOL.get(UID).isOpen()) {
        Channel channel = conn.createChannel();
        channel.exchangeDeclare(RabbitMQConstants.EXCHANGE, "direct", true);
        if (queueIn != null) {
            channel.queueDeclare(queueIn, false, false, true, null);
            channel.queueBind(queueIn, RabbitMQConstants.EXCHANGE, routingKeyIn);
        }//from   w ww  .  j a  v  a2 s.  co  m
        if (queueOut != null) {
            channel.queueDeclare(queueOut, false, false, true, null);
            channel.queueBind(queueOut, RabbitMQConstants.EXCHANGE, routingKeyOut);
        }

        POOL.put(UID, channel);
    }

    return POOL.get(UID);
}

From source file:it.jugtorino.one.msvc.way.rabbit.geoip.reference.client.RpcClientExample.java

License:Open Source License

private static Channel setupRabbitMQ() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    Connection connection = factory.newConnection(Collections.singletonList(new Address("localhost")));
    Channel channel = connection.createChannel();
    channel.queueDeclare("geoip_service_v1", false, false, false, null);
    return channel;
}

From source file:it.jugtorino.one.msvc.way.rabbit.geoip.reference.service.Main.java

License:Open Source License

private static Channel setupRabbitMQ() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    Connection connection = factory.newConnection(Arrays.asList(new Address("localhost")));
    Channel channel = connection.createChannel();
    channel.queueDeclare("geoip_service_v1", false, false, false, null);
    return channel;
}