Example usage for com.rabbitmq.client Channel basicQos

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

Introduction

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

Prototype

void basicQos(int prefetchCount) throws IOException;

Source Link

Document

Request a specific prefetchCount "quality of service" settings for this channel.

Usage

From source file:org.trpr.mule.transport.rabbitmq.RabbitConnector.java

License:Apache License

/**
 * Creates and returns a ChannelHolder object for the specified endpoint.
 * @param endpoint declared Mule endpoint
 * @return a ChannelHolder instance containing the Connection
 * @throws IOException in case of I/O errors
 * @throws InitialisationException in case of initialization errors
 *//*from  w w w  .  j a  v  a  2s  .c o m*/
public synchronized ChannelHolder createChannel(ImmutableEndpoint endpoint)
        throws IOException, InitialisationException {
    Channel channel = connection.createChannel();
    if (channel == null) {
        throw new InitialisationException(CoreMessages.failedToCreate(Channel.class.getName()), null);
    }
    // check if a pre-fetch count has been explicitly set and set it on the channel, else ignore        
    if (this.getPrefetchCount() != RabbitConnector.DEFAULT_PREFETCH_COUNT) {
        channel.basicQos(this.getPrefetchCount());
    }

    // set the newly created channel in txSelect mode if the endpoint is marked as durable and is of 
    // type OutboundEndPoint. TX is not supported for inbound end-points. Acking is preferred mechanism
    // for control over message consumption i.e. in RabbitMessageReceiver
    if (EndpointUtils.getDurable(endpoint) && endpoint instanceof OutboundEndpoint) {
        channel.txSelect();
    }
    return new ChannelHolder(channel);
}

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);//w ww  .jav a2 s . co m
    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.event.adapter.rabbitmq.internal.util.RabbitMQOutputEventAdapterPublisher.java

License:Open Source License

/**
 * <pre>// w w w.  j a v  a  2  s.co  m
 * get channel
 * </pre>
 *
 * @return
 */
public Channel getChannel() {
    LOGGER.debug("*** DEBUG RabbitMQOutputEventAdaptorType.getChannel() start.");

    Channel channel = cache.get(tenantId);

    if (channel == null || !channel.isOpen()) {
        String hostName = eventAdapterConfiguration.getHostName();
        String port = eventAdapterConfiguration.getPort();
        String password = eventAdapterConfiguration.getPassword();
        String userName = eventAdapterConfiguration.getUsername();
        String virtualHost = eventAdapterConfiguration.getVirtualHostName();

        ConnectionFactory factory = this.getConnectionFactory(hostName, Integer.parseInt(port), userName,
                password, virtualHost);

        LOGGER.debug("*** DEBUG: RabbitMQOutputEventAdapterType.getChannel() hostName=" + hostName);
        LOGGER.debug("*** DEBUG: RabbitMQOutputEventAdapterType.getChannel() port=" + port);
        LOGGER.debug("*** DEBUG: RabbitMQOutputEventAdapterType.getChannel() userName=" + userName);
        LOGGER.debug("*** DEBUG: RabbitMQOutputEventAdapterType.getChannel() password=" + password);
        LOGGER.debug("*** DEBUG: RabbitMQOutputEventAdapterType.getChannel() virtualHost=" + virtualHost);
        LOGGER.debug("*** DEBUG: RabbitMQOutputEventAdapterType.getChannel() tenantId=" + tenantId);

        try {
            if (connection == null || !connection.isOpen()) {
                connection = factory.newConnection();
            }

            /**
             * Multiple operations into Channel instance are serialized and thread-safe
             */
            channel = connection.createChannel();
            channel.basicQos(1);
            cache.put(tenantId, channel);
        } catch (IOException e) {
            LOGGER.warn("Failed to create communication channel", e);
            throw new RabbitAdapterMQException(e);
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }

    return channel;
}

From source file:org.wso2.carbon.event.adapter.rabbitmq.output.RabbitMQOutputEventAdapter.java

License:Open Source License

/**
 * This method is used to test the connection of the publishing server.
 *
 * @throws TestConnectionNotSupportedException
 */// w w w .j a  v  a2  s . co m
@Override
public void testConnect() throws TestConnectionNotSupportedException {
    //        throw new TestConnectionNotSupportedException("Test connection is not available");
    tenantId = Integer.parseInt(eventAdapterConfiguration.getStaticProperties()
            .get(RabbitMQOutputEventAdapterConstants.RABBITMQ_TENANT_NAME));
    RabbitMQOutputEventAdapterConnectionConfiguration rabbitMQOutputEventAdapterConnectionConfiguration = new RabbitMQOutputEventAdapterConnectionConfiguration(
            eventAdapterConfiguration.getStaticProperties()
                    .get(RabbitMQOutputEventAdapterConstants.RABBITMQ_SERVER_HOST_NAME),
            eventAdapterConfiguration.getStaticProperties()
                    .get(RabbitMQOutputEventAdapterConstants.RABBITMQ_SERVER_VIRTUAL_HOST),
            eventAdapterConfiguration.getStaticProperties()
                    .get(RabbitMQOutputEventAdapterConstants.RABBITMQ_SERVER_PORT),
            eventAdapterConfiguration.getStaticProperties()
                    .get(RabbitMQOutputEventAdapterConstants.RABBITMQ_SERVER_USERNAME),
            eventAdapterConfiguration.getStaticProperties()
                    .get(RabbitMQOutputEventAdapterConstants.RABBITMQ_SERVER_PASSWORD),
            eventAdapterConfiguration.getStaticProperties()
                    .get(RabbitMQOutputEventAdapterConstants.RABBITMQ_QUEUE_NAME));

    RabbitMQOutputEventAdapterPublisher rabbitMQOutputEventAdapterPublisher = new RabbitMQOutputEventAdapterPublisher(
            rabbitMQOutputEventAdapterConnectionConfiguration, tenantId);

    Channel channel = rabbitMQOutputEventAdapterPublisher.getChannel();

    try {
        channel.basicQos(1);
    } catch (IOException e) {
        throw new RabbitAdapterMQException(e);
    }
}

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

License:Open Source License

/**
 * <pre>/*from   w w  w.  j  a  v a 2  s  .  co m*/
 * testConnection
 * <pre>
 * 
 * @param outputEventAdaptorConfiguration
 * @param tenantId
 * @see org.wso2.carbon.event.output.adaptor.core.AbstractOutputEventAdaptor#testConnection(org.wso2.carbon.event.output.adaptor.core.config.OutputEventAdaptorConfiguration, int)
 */
@Override
public void testConnection(OutputEventAdaptorConfiguration outputEventAdaptorConfiguration, int tenantId) {
    Channel channel = getChannel(outputEventAdaptorConfiguration, tenantId);
    try {
        channel.basicQos(1);
    } catch (IOException e) {
        throw new AdaptorRuntimeException(e);
    }
}

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

License:Open Source License

/**
 * <pre>// www  . ja  v  a2s.c o  m
 * get channel
 * </pre>
 * 
 * @param outputEventAdaptorConfiguration
 * @param tenantId
 * @return
 */
Channel getChannel(OutputEventAdaptorConfiguration outputEventAdaptorConfiguration, int tenantId) {
    Map<String, String> brokerProperties = outputEventAdaptorConfiguration.getOutputProperties();
    LOGGER.debug("*** DEBUG RabbitMQOutputEventAdaptorType.getChannel() " + brokerProperties);

    Channel channel = cache.get(tenantId);
    if (channel == null || !channel.isOpen()) {
        String hostName = brokerProperties.get(RabbitMQEventAdaptorConstants.ADAPTOR_RABBITMQ_HOSTNAME);
        String port = brokerProperties.get(RabbitMQEventAdaptorConstants.ADAPTOR_RABBITMQ_PORT);
        String password = brokerProperties.get(RabbitMQEventAdaptorConstants.ADAPTOR_RABBITMQ_PASSWORD);
        String userName = brokerProperties.get(RabbitMQEventAdaptorConstants.ADAPTOR_RABBITMQ_USERNAME);
        String virtualHost = brokerProperties.get(RabbitMQEventAdaptorConstants.ADAPTOR_RABBITMQ_VIRTUALHOST);

        ConnectionFactory factory = EventAdapterHelper.getConnectionFactory(hostName, Integer.parseInt(port),
                userName, password, virtualHost);

        LOGGER.debug("*** DEBUG: RabbitMQOutputEventAdaptorType.getChannel() hostName=" + hostName);
        LOGGER.debug("*** DEBUG: RabbitMQOutputEventAdaptorType.getChannel() port=" + port);
        LOGGER.debug("*** DEBUG: RabbitMQOutputEventAdaptorType.getChannel() userName=" + userName);
        LOGGER.debug("*** DEBUG: RabbitMQOutputEventAdaptorType.getChannel() password=" + password);
        LOGGER.debug("*** DEBUG: RabbitMQOutputEventAdaptorType.getChannel() virtualHost=" + virtualHost);
        LOGGER.debug("*** DEBUG: RabbitMQOutputEventAdaptorType.getChannel() tenantId=" + tenantId);

        try {
            if (connection == null || !connection.isOpen()) {
                connection = factory.newConnection();
            }

            /**
             * Multiple operations into Channel instance are serialized and thread-safe
             */
            channel = connection.createChannel();
            channel.basicQos(1);
            cache.put(tenantId, channel);
        } catch (IOException e) {
            LOGGER.warn("Failed to create communication channel", e);
            throw new AdaptorRuntimeException(e);
        }
    }

    return channel;
}

From source file:org.wso2.siddhi.debs2017.input.DebsBenchmarkSystem.java

License:Open Source License

private RabbitQueue createQueueWithName(String name, ExecutorService executorService) throws Exception {
    Channel channel = createConnection(executorService).createChannel();
    channel.basicQos(getPrefetchCount());
    channel.queueDeclare(name, false, false, true, null);
    return new RabbitQueue(channel, name);
}

From source file:ox.softeng.burst.service.message.RabbitMessageService.java

@Override
public void run() {
    for (int c = 0; c < consumerCount; c++) {
        try {/*from w  ww . j av  a2 s  . com*/
            Channel channel = connection.createChannel();
            channel.basicQos(40);
            channel.exchangeDeclare(exchange, "topic", true);
            Consumer consumer = new MessageConsumer(channel, entityManagerFactory);
            channel.basicConsume(queue, true, consumer);
        } catch (IOException e) {
            logger.error("Error running consumer for queue '" + queue + "'", e);
        } catch (Exception e) {
            logger.error("Unhandled exception: " + e.getMessage(), e);
        }
    }
}

From source file:ox.softeng.burst.services.RabbitService.java

License:Open Source License

public void run() {
    try {/*w  w  w  .j a v a 2s.  c  o  m*/
        Channel channel = connection.createChannel();
        channel.basicQos(40);
        channel.exchangeDeclare(rabbitMQExchange, "topic", true);
        Consumer consumer = createConsumer(channel);
        logger.warn("Waiting for messages");
        channel.basicConsume(rabbitMQQueue, true, consumer);
    } catch (IOException e) {
        logger.error("Error running consumer for queue '" + rabbitMQQueue + "'", e);
    } catch (Exception e) {
        logger.error("Unhandled exception: " + e.getMessage(), e);
    }
}

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

License:Apache License

/**
 * Creates the channel.//ww  w . j av a2  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) {
            }
        }
    }
}