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:ThreadWorkers.java

public void run() {
    System.out.println("MyThread running");

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = null;
    try {/*w w w .j ava2 s .  c o m*/
        connection = factory.newConnection();
    } catch (IOException ex) {
        Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex);
    }
    Channel channel = null;
    try {
        channel = connection.createChannel();
    } catch (IOException ex) {
        Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
    } catch (IOException ex) {
        Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    try {
        channel.basicQos(1);
    } catch (IOException ex) {
        Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex);
    }

    QueueingConsumer consumer = new QueueingConsumer(channel);
    try {
        channel.basicConsume(TASK_QUEUE_NAME, false, consumer);
    } catch (IOException ex) {
        Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex);
    }

    while (true) {
        QueueingConsumer.Delivery delivery = null;
        try {
            delivery = consumer.nextDelivery();
        } catch (InterruptedException ex) {
            Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ShutdownSignalException ex) {
            Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ConsumerCancelledException ex) {
            Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex);
        }
        String message = new String(delivery.getBody());

        System.out.println(" [x] Received '" + message + "'");
        try {

            doWork(message);
        } catch (InterruptedException ex) {
            Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println(" [x] Done");

        try {
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        } catch (IOException ex) {
            Logger.getLogger(ThreadWorkers.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:ReplyUtil.java

public void getReply() throws IOException, InterruptedException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.queueDeclare(TASK_QUEUE_REPLY_NAME, true, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    channel.basicQos(1);

    QueueingConsumer consumer2 = new QueueingConsumer(channel);
    channel.basicConsume(TASK_QUEUE_REPLY_NAME, false, consumer2);

    while (true) {
        QueueingConsumer.Delivery delivery = consumer2.nextDelivery();
        String message = new String(delivery.getBody());

        System.out.println(" [x] Receiving reply from worker::'" + message + "'");
        //doWork(message); 
        //System.out.println(" [x] Done" );

        channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);

    }//w ww.  j a  va 2 s. c o m

}

From source file:com.digispherecorp.enterprise.rabbitmq.ra.work.QueueRabbitMQWork.java

@Override
public void run() {
    try {/*from  w w w .jav  a  2  s  .  c  om*/

        Logger.getLogger(QueueRabbitMQWork.class.getName()).log(Level.INFO,
                "Work Schedule Polling started @ ".concat(uuid));

        final Channel channel;
        RabbitMQConnectionFactoryFacade instance = RabbitMQConnectionFactoryFacade.getInstance();
        if (instance.getConnectionRequestInfo(activationSpec) == null) {
            instance.setConnectionRequestInfo(activationSpec,
                    new RabbitMQConnectionRequestInfo(((RabbitMQActivationSpec) activationSpec).getUser(),
                            ((RabbitMQActivationSpec) activationSpec).getPassword(),
                            ((RabbitMQActivationSpec) activationSpec).getHost(),
                            ((RabbitMQActivationSpec) activationSpec).getPort(),
                            ((RabbitMQActivationSpec) activationSpec).getVirtualHost()));
        }
        try {
            connection = instance.getConnection();
            channel = connection.createChannel();
            channel.queueDeclarePassive(((RabbitMQActivationSpec) activationSpec).getQueueName());
            channel.basicQos(0);

            final Consumer consumer = new DefaultConsumer(channel) {

                @Override
                public void handleConsumeOk(String consumerTag) {
                    super.handleConsumeOk(consumerTag);
                }

                @Override
                public void handleDelivery(String consumerTag, Envelope envelope,
                        AMQP.BasicProperties properties, byte[] body) throws IOException {
                    super.handleDelivery(consumerTag, envelope, properties, body);

                    if (!envelope.isRedeliver()) {
                        try {
                            RabbitMQMessage mQMessage = new RabbitMQMessage();
                            mQMessage.getMessages().add(body);
                            try {
                                receiveMessages(mQMessage);
                            } catch (ResourceException ex) {
                                Logger.getLogger(QueueRabbitMQWork.class.getName()).log(Level.SEVERE,
                                        ex.getLocalizedMessage(), ex);
                            }
                        } finally {
                            channel.basicAck(envelope.getDeliveryTag(), true);
                        }
                    }
                }
            };
            channel.basicConsume(((RabbitMQActivationSpec) activationSpec).getQueueName(), false, consumer);
        } catch (IOException ex) {
            Logger.getLogger(RabbitMQResourceAdapter.class.getName()).log(Level.SEVERE,
                    ex.getLocalizedMessage(), ex);
        }
    } catch (Exception ex) {
        Logger.getLogger(QueueRabbitMQWork.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex);
    }
}

From source file:com.flipkart.bifrost.framework.impl.RabbitMQBifrostExecutor.java

License:Apache License

RabbitMQBifrostExecutor(Connection connection, ExecutorService executorService, int concurrency,
        ObjectMapper objectMapper, String requestQueue, String replyQueueName, long responseWaitTimeout)
        throws Exception {
    if (null == connection || null == connection.getConnection()) {
        throw new BifrostException(BifrostException.ErrorCode.INVALID_CONNECTION,
                "The provided connection is invalid. Call start() on connection to start it.");
    }//from   w w w.  j a va 2 s  . com
    this.executorService = executorService;
    this.objectMapper = objectMapper;
    this.requestQueue = requestQueue;
    this.replyQueueName = replyQueueName;
    this.publishChannel = connection.getConnection().createChannel();
    this.responseWaitTimeout = responseWaitTimeout;
    AMQP.Queue.DeclareOk requestQueueResponse = publishChannel.queueDeclare(requestQueue, true, false, false,
            Collections.<String, Object>singletonMap("x-ha-policy", "all"));
    AMQP.Queue.DeclareOk replyQueue = publishChannel.queueDeclare(replyQueueName, true, false, false,
            Collections.<String, Object>singletonMap("x-ha-policy", "all"));
    for (int i = 0; i < concurrency; i++) {
        Channel channel = connection.getConnection().createChannel();
        channel.basicQos(1);
        ReplyListener<T> listener = new ReplyListener<T>(channel, waiters, handlers, objectMapper);
        channel.basicConsume(replyQueueName, listener);
        listeners.add(listener);
    }
}

From source file:com.flipkart.bifrost.framework.impl.RabbitMQBifrostRemoteCallExecutionServer.java

License:Apache License

@Override
public void start() throws BifrostException {
    try {//from w w  w .j  a v a  2  s  .  c  o  m
        if (null == connection || null == connection.getConnection()) {
            throw new BifrostException(BifrostException.ErrorCode.INVALID_CONNECTION,
                    "The provided connection is invalid. Call start() on connection to start it.");
        }
        for (int i = 1; i <= concurrency; i++) {
            Channel channel = connection.getConnection().createChannel();
            RabbitMQExecutionServerListener<T> listener = new RabbitMQExecutionServerListener<T>(channel,
                    mapper);
            channel.basicQos(1);
            channel.basicConsume(requestQueue, listener);
            listeners.add(listener);
        }
    } catch (IOException e) {
        throw new BifrostException(BifrostException.ErrorCode.IO_ERROR, "Error registering listener", e);
    }
}

From source file:com.github.liyp.rabbitmq.rpc.RPCServer.java

License:Apache License

public static void main(String[] argv) {
    Connection connection = null;
    Channel channel = null;
    try {/*from  w  w w  .ja va2 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(" [x] Awaiting RPC requests");

        while (true) {
            String response = null;

            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");
                int n = Integer.parseInt(message);

                System.out.println(" [.] fib(" + message + ")");
                response = "" + fib(n);
            } catch (Exception e) {
                System.out.println(" [.] " + e.toString());
                response = "";
            } finally {
                channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes("UTF-8"));

                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ignore) {
            }
        }
    }
}

From source file:com.hopped.running.demo.RunServer.java

License:Open Source License

/**
 * //w ww  .  j  av a 2 s  .co m
 * @param args
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    final String queueName = "runningRabbit";

    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.basicQos(1);
    channel.queueDeclare(queueName, false, false, false, null);

    ProtobufRPCServer server = new ProtobufRPCServer(channel, queueName).init()
            .setInstance(new RunnerServiceImpl()).setProtocol(IRunnerService.class);
    server.consume();
}

From source file:com.mycompany.javateste.queues.worktasks.Worker.java

public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    final Connection connection = factory.newConnection();
    final Channel channel = connection.createChannel();

    channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    channel.basicQos(1);

    final Consumer consumer = new DefaultConsumer(channel) {
        @Override/* w  w  w  . j  a v  a2s  . com*/
        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 + "'");
            try {
                doWork(message);
            } finally {
                System.out.println(" [x] Done");
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        }
    };
    channel.basicConsume(TASK_QUEUE_NAME, false, consumer);
}

From source file:com.netcore.hsmart.dlrconsumers.DlrConsumer1000.java

/**
 * @param args the command line arguments
 * @throws java.lang.Exception//from ww w.  j a v  a2  s. c om
 */
public static void main(String[] args) throws Exception {

    /**
     * Set properties at runtime
     */
    System.setProperty("dlrconsumer_logfile", "557_dlr_consumer.log");
    AppConstants.loadAppConfig();

    final String queueName = AppConstants.getDlrReceiverQueuePrefix() + GATEWAY_ID;
    final String exchangeName = AppConstants.getDlrReceiverExchangeName();
    final String routingKey = GATEWAY_ID;

    Logger logger = LoggerFactory.getLogger(DlrConsumer1000.class);

    try {

        Connection connection = AppConstants.getRabbitMqObject().newConnection();

        connection.addShutdownListener(new ShutdownListener() {
            @Override
            public void shutdownCompleted(ShutdownSignalException cause) {
                //throw new UnsupportedOperationException("Not supported yet.");
                if (cause.isHardError()) {
                    Connection conn;
                    conn = (Connection) cause.getReference();
                    if (!cause.isInitiatedByApplication()) {
                        Method reason = cause.getReason();
                        logger.info("REASON:" + reason.toString());
                    }

                } else {
                    Channel ch = (Channel) cause.getReference();
                    logger.info("NO HARDSHUTDOWN");
                }
            }
        });

        Channel channel = connection.createChannel();

        channel.exchangeDeclare(exchangeName, "direct");
        channel.queueDeclare(queueName, true, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);
        channel.basicQos(1000);
        //channel.addShutdownListener(listener);
        logger.info(" [*] Waiting for messages from gateway " + GATEWAY_ID + ". To exit press CTRL+C");

        Consumer consumer;

        consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {

                Map<String, String> dataToPost = new HashMap<>();
                String payload = new String(body, "UTF-8");

                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|START+++++++++++++++");
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|PAYLOAD:" + payload);

                String payloadParts[] = payload.split(AppConstants.getPayloadGroupSeparator());

                for (String payloadPart : payloadParts) {
                    String s[] = payloadPart.split(AppConstants.getPayloadKVSeparator());

                    //check if any parameter is empty
                    if (s.length == 2) {
                        dataToPost.put(s[0], s[1]);
                    } else {
                        logger.info("REF_ID:" + dataToPost.get("ref_id") + "|EMPTY_PARAM:" + s[0]);
                        dataToPost.put(s[0], null);
                    }
                }

                long deliveryTag = envelope.getDeliveryTag();

                if (invokeApiCall(dataToPost)) {
                    channel.basicAck(deliveryTag, false);

                } else {
                    channel.basicNack(deliveryTag, false, true);
                }

                /**
                 * release memory
                 */
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|END-----------------");
                dataToPost.clear();
                payloadParts = null;

            }
        };

        String cTag = channel.basicConsume(queueName, false, consumer);
        logger.info("CONSUMER TAG : " + cTag);

    } catch (IOException | TimeoutException e) {
        logger.error("RMQ_ERROR:" + e.getMessage());
    }
}

From source file:com.netcore.hsmart.smsconsumers.SmsConsumer1000.java

/**
 * @param args the command line arguments
 * @throws java.lang.Exception//w  w w . j a v  a 2  s .  c o  m
 */
public static void main(String[] args) throws Exception {

    /**
     * Set properties at runtime
     */
    System.setProperty("smsconsumer_logfile", GATEWAY_ID + "_sms_consumer.log");
    AppConstants.loadAppConfig();

    final String queueName = AppConstants.getSmsReceiverQueuePrefix() + GATEWAY_ID;
    final String exchangeName = AppConstants.getSmsReceiverExchangeName();
    final String routingKey = GATEWAY_ID;

    Logger logger = LoggerFactory.getLogger(SmsConsumer1000.class);

    try {

        Connection connection = AppConstants.getRabbitMqObject().newConnection();

        connection.addShutdownListener(new ShutdownListener() {
            @Override
            public void shutdownCompleted(ShutdownSignalException cause) {
                //throw new UnsupportedOperationException("Not supported yet.");
                if (cause.isHardError()) {
                    Connection conn;
                    conn = (Connection) cause.getReference();
                    if (!cause.isInitiatedByApplication()) {
                        Method reason = cause.getReason();
                        logger.info("REASON:" + reason.toString());
                    }

                } else {
                    Channel ch = (Channel) cause.getReference();
                    logger.info("NO HARDSHUTDOWN");
                }
            }
        });

        Channel channel = connection.createChannel();

        channel.exchangeDeclare(exchangeName, "direct");
        channel.queueDeclare(queueName, true, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);
        channel.basicQos(1000);
        //channel.addShutdownListener(listener);
        logger.info(" [*] Waiting for messages from gateway " + GATEWAY_ID + ". To exit press CTRL+C");

        Consumer consumer;

        consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                    byte[] body) throws IOException {

                Map<String, String> dataToPost = new HashMap<>();
                String payload = new String(body, "UTF-8");

                String payloadParts[] = payload.split(AppConstants.getPayloadGroupSeparator());

                for (String payloadPart : payloadParts) {
                    String s[] = payloadPart.split(AppConstants.getPayloadKVSeparator());
                    dataToPost.put(s[0], s[1]);
                }
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|START+++++++++++++++");
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|PAYLOAD:" + payload);

                long deliveryTag = envelope.getDeliveryTag();

                if (invokeApiCall(dataToPost)) {
                    if (saveRequestData()) {

                        channel.basicAck(deliveryTag, false);
                    } else {
                        channel.basicNack(deliveryTag, false, true);
                    }

                } else {
                    channel.basicNack(deliveryTag, false, true);
                }

                /**
                 * release memory
                 */
                logger.info("REF_ID:" + dataToPost.get("ref_id") + "|END-----------------");
                API_CALL_STATS.clear();
                dataToPost.clear();
                payloadParts = null;

            }
        };

        String cTag = channel.basicConsume(queueName, false, consumer);
        logger.info("CONSUMER TAG : " + cTag);

    } catch (IOException | TimeoutException e) {
        logger.error("RMQ_ERROR:" + e.getMessage());
    }
}