Example usage for com.rabbitmq.client Channel queueBind

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

Introduction

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

Prototype

Queue.BindOk queueBind(String queue, String exchange, String routingKey) throws IOException;

Source Link

Document

Bind a queue to an exchange, with no extra arguments.

Usage

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 w  w w.  j  av  a  2 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.wso2.carbon.caching.invalidator.amqp.CacheInvalidationSubscriber.java

License:Open Source License

private void subscribe() {
    log.debug("Global cache invalidation: initializing the subscription");
    try {/*w  ww .  ja  v  a  2 s . com*/
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(ConfigurationManager.getProviderUrl());
        int port = Integer.parseInt(ConfigurationManager.getProviderPort());
        factory.setPort(port);
        factory.setUsername(ConfigurationManager.getProviderUsername());
        factory.setPassword(ConfigurationManager.getProviderPassword());
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(ConfigurationManager.getTopicName(), "topic");
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, ConfigurationManager.getTopicName(), "#");
        consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, true, consumer);
        Thread reciever = new Thread(messageReciever);
        reciever.start();
        log.info("Global cache invalidation is online");
    } catch (Exception e) {
        log.error("Global cache invalidation: Error message broker initialization", e);
    }
}

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

License:Open Source License

/**
 * <pre>/*  w ww.  j  a v  a  2 s  .com*/
 * 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:pl.nask.hsn2.bus.rabbitmq.RbtUtils.java

License:Open Source License

/**
 * Creates single queue.//from  www . j  a v  a 2s.  com
 * 
 * @param channel Channel to create a queue.
 * @param queueName Name of the queue to be created.
 * @throws BusException Any problem will rise the exception.
 */
public static void createQueue(Channel channel, String servicesExchangeName, String queueName)
        throws BusException {
    try {
        channel.queueDeclare(queueName, false, false, false, null);
        channel.queueBind(queueName, servicesExchangeName, queueName);
    } catch (IOException e) {
        throw new BusException("Can not create queue: " + queueName, e);
    }
}

From source file:pl.nask.hsn2.bus.rabbitmq.RbtUtils.java

License:Open Source License

/**
 * Creates single queue./*from w w  w  . j  a  v  a 2s.co  m*/
 * 
 * @param connection Connection to Rabbit MQ server.
 * @param queueName Name of the queue to be created.
 * @throws BusException Any problem will rise the exception.
 */
public static void createQueue(Connection connection, String servicesExchangeName, String queueName)
        throws BusException {
    Channel channel = null;
    try {
        channel = createChannel(connection);
        channel.queueDeclare(queueName, false, false, false, null);
        channel.queueBind(queueName, servicesExchangeName, queueName);
    } catch (IOException e) {
        throw new BusException("Can not create queue: " + queueName, e);
    } finally {
        closeChannel(channel);
    }
}

From source file:pl.nask.hsn2.DataStoreActiveCleaner.java

License:Open Source License

/**
 * Initialize RabbitMQ connection./*from  w w w  .j ava2 s .co m*/
 *
 * @return RabbitMQ consumer.
 * @throws IOException
 *             When there's some connection issues.
 */
private QueueingConsumer initRabbitMqConnection() throws IOException {
    ConnectionFactory connFactory = new ConnectionFactory();
    connFactory.setHost(rbtHostName);
    rbtConnection = connFactory.newConnection();
    Channel channel = rbtConnection.createChannel();
    channel.exchangeDeclare(rbtNotifyExchName, "fanout");
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, rbtNotifyExchName, "");
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, AUTO_ACK, consumer);
    return consumer;
}

From source file:play.modules.rabbitmq.RabbitMQPlugin.java

License:Apache License

/**
 * Creates the channel.//from ww w . j  ava 2 s  .c  om
 * 
 * @param queue
 *            the queue
 * @return the channel
 * @throws Exception
 *             the exception
 */
public Channel createChannel(String queue, String routingKey) throws Exception {
    // Counter that keeps track of number of retries
    int attempts = 0;

    // Get Plugin
    RabbitMQPlugin plugin = Play.application().plugin(RabbitMQPlugin.class);

    // Create Channel
    Channel channel = this.createChannel();

    // Basic Qos
    if (RabbitMQPlugin.isBasicQos()) {
        int prefetchCount = 1;
        channel.basicQos(prefetchCount);
    }

    // Start Daemon
    while (true) {
        // Add to the number of retries
        attempts++;

        // Log Debug
        Logger.debug("Retry " + attempts);

        // Get Next Delivery Message
        try {
            // http://www.rabbitmq.com/api-guide.html
            // channel.exchangeDeclare(exchangeName, "direct", true);
            // String queueName = channel.queueDeclare().getQueue();
            // channel.queueBind(queueName, exchangeName, routingKey);

            channel.exchangeDeclare(queue, plugin.getExchangeType(), true);
            channel.queueDeclare(queue, plugin.isDurable(), false, false, null);
            channel.queueBind(queue, queue, routingKey);

            // Log Debug
            Logger.info("RabbitMQ Task Channel Available: " + channel);

            // Return Channel
            return channel;

        } catch (Throwable t) {
            // Log Debug
            Logger.error("Error establishing a connection to RabbitMQ, will keep retrying - Exception: %s",
                    ExceptionUtil.getStackTrace(t));

            // Sleep a little while before retrying
            try {
                Thread.sleep(1000 * 10);
            } catch (InterruptedException ex) {
            }
        }
    }
}

From source file:play.modules.rabbitmq.RabbitMQPlugin.java

License:Apache License

/**
    * Creates the channel for a subscriber to consume messages from an exchange
    * (Exchange is created.  Subscribers queue and binding by routing key are created)
    * /*w  w w .jav  a 2 s.  c o  m*/
    * @param exchangeName
    *            the exchange name
    * @param queue
    *            the queue
    * @param routingKey
    *            the routing key
    * @return the channel
    * @throws Exception
    *             the exception
    */
public Channel createSubscribersChannel(String exchangeName, String queue, String routingKey) throws Exception {
    // Counter that keeps track of number of retries
    int attempts = 0;

    // Get Plugin
    RabbitMQPlugin plugin = Play.application().plugin(RabbitMQPlugin.class);

    // Create Channel
    Channel channel = this.createChannel();

    // Basic Qos
    if (RabbitMQPlugin.isBasicQos()) {
        int prefetchCount = 1;
        channel.basicQos(prefetchCount);
    }

    // Start Daemon
    while (true) {
        // Add to the number of retries
        attempts++;

        // Log Debug
        Logger.debug("Retry " + attempts);

        // Get Next Delivery Message
        try {
            // http://www.rabbitmq.com/api-guide.html
            channel.exchangeDeclare(exchangeName, plugin.getExchangeType(), true);
            channel.queueDeclare(queue, plugin.isDurable(), false, false, null);
            channel.queueBind(queue, exchangeName, routingKey);

            // Log Debug
            Logger.info("RabbitMQ Task Channel Available: " + channel);

            // Return Channel
            return channel;

        } catch (Throwable t) {
            // Log Debug
            Logger.error("Error establishing a connection to RabbitMQ, will keep retrying - Exception: %s",
                    ExceptionUtil.getStackTrace(t));

            // Sleep a little while before retrying
            try {
                Thread.sleep(1000 * 10);
            } catch (InterruptedException ex) {
            }
        }
    }
}

From source file:pro.foundev.examples.spark_streaming.java.interactive.querybasedconsumer.QueryConsumer.java

License:Apache License

public void run() {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
    final Session session = cluster.connect();
    session.execute(String.format("CREATE TABLE IF NOT EXISTS tester.warningsrdd (ssn text, "
            + "batchStartTime bigint, id uuid, amount decimal, rule text, PRIMARY KEY(batchStartTime, id))"));
    final PreparedStatement preparedStatement = session
            .prepare("SELECT * FROM tester.warningsrdd where batchStartTime = ?");
    try {/*from w  ww  . j  a  va  2 s . co  m*/
        Connection connection = factory.newConnection();
        final Channel channel = connection.createChannel();
        final String queue = channel.queueDeclare().getQueue();
        channel.queueBind(queue, EXCHANGE_NAME, "");

        final 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);
                long batchStartTime = Long.parseLong(message);
                System.out.println("Writing batch with start time of " + new Date(batchStartTime));
                ResultSet warningsResultSet = session.execute(preparedStatement.bind(batchStartTime));
                int count = 0;
                for (Row warning : warningsResultSet) {
                    count += 1;
                    BigDecimal decimal = warning.getDecimal("amount");
                    UUID id = warning.getUUID("id");
                    String ssn = warning.getString("ssn");
                    String rule = warning.getString("rule");
                    Warning warningObj = new Warning();
                    warningObj.setAmount(decimal);
                    warningObj.setId(id);
                    warningObj.setSsn(ssn);
                    warningObj.setRule(rule);
                    notifyUI(warningObj);
                }
                System.out.println("Batch with start time of " + new Date(batchStartTime) + " Complete with "
                        + count + " items.");
            }
        };
        channel.basicConsume(queue, true, consumer);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:pt.ua.ies.ControllerView.java

@PostConstruct
public void init() {
    System.out.println("init");
    recive = "";/*w  w w  .j  a v a  2 s  .  c o  m*/
    reciveBeforeRefresh = recive;
    try {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");

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

        channel.exchangeDeclare(DisplayMessage.EXCHANGE_NAME, "fanout");
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, DisplayMessage.EXCHANGE_NAME, "");

        MessageConsumer m = new MessageConsumer(channel, this);

        channel.basicConsume(queueName, true, m);
    } catch (Exception ex) {
        Logger.getLogger(ControllerView.class.getName()).log(Level.SEVERE, null, ex);
    }
}