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:in.cs654.chariot.turagraksa.ZooKeeperServer.java

License:Open Source License

public static void main(String[] args) {
    Connection connection = null;
    Channel channel;
    try {//  ww w. j a  v  a  2s .  c o m
        final ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(HOST_IP_ADDR);
        connection = factory.newConnection();
        channel = connection.createChannel();
        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
        channel.basicQos(1);

        final QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
        LOGGER.info("ZooKeeper Server started. Waiting for requests...");
        ZooKeeper.startPingEcho();

        while (true) {
            final QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            BasicResponse response = new BasicResponse();
            BasicRequest request = new BasicRequest();
            final AMQP.BasicProperties props = delivery.getProperties();
            final AMQP.BasicProperties replyProps = new AMQP.BasicProperties.Builder()
                    .correlationId(props.getCorrelationId()).build();
            try {
                final DatumReader<BasicRequest> avroReader = new SpecificDatumReader<BasicRequest>(
                        BasicRequest.class);
                decoder = DecoderFactory.get().binaryDecoder(delivery.getBody(), decoder);
                request = avroReader.read(request, decoder);
                response = ZooKeeperProcessor.process(request);

            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.severe("Error in handling request: " + e.getMessage());
                response = ResponseFactory.getErrorResponse(request);

            } finally {
                baos.reset();
                final DatumWriter<BasicResponse> avroWriter = new SpecificDatumWriter<BasicResponse>(
                        BasicResponse.class);
                encoder = EncoderFactory.get().binaryEncoder(baos, encoder);
                avroWriter.write(response, encoder);
                encoder.flush();
                channel.basicPublish("", props.getReplyTo(), replyProps, baos.toByteArray());
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        LOGGER.severe("Error in RPC server: " + e.getMessage());
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ignore) {
            }
        }
    }
}

From source file:info.pancancer.arch3.utils.Utilities.java

License:Open Source License

/**
 * Clears database state and known queues for testing.
 *
 * @param settings//w  ww.  java2 s .  c  om
 * @throws IOException
 * @throws java.util.concurrent.TimeoutException
 */
public static void clearState(HierarchicalINIConfiguration settings) throws IOException, TimeoutException {
    File configFile = FileUtils.getFile("src", "test", "resources", "config");
    HierarchicalINIConfiguration parseConfig = Utilities.parseConfig(configFile.getAbsolutePath());
    PostgreSQL postgres = new PostgreSQL(parseConfig);
    // clean up the database
    postgres.clearDatabase();

    String server = settings.getString(Constants.RABBIT_HOST);
    String user = settings.getString(Constants.RABBIT_USERNAME);
    String pass = settings.getString(Constants.RABBIT_PASSWORD);

    Channel channel;

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(server);
    factory.setUsername(user);
    factory.setPassword(pass);
    factory.setAutomaticRecoveryEnabled(true);
    Connection connection = factory.newConnection();
    channel = connection.createChannel();
    channel.basicQos(1);
    channel.confirmSelect();

    String prefix = settings.getString(Constants.RABBIT_QUEUE_NAME);
    String[] queues = { prefix + "_jobs", prefix + "_orders", prefix + "_vms", prefix + "_for_CleanupJobs",
            prefix + "_for_CleanupVMs" };
    for (String queue : queues) {
        try {
            channel.queueDelete(queue);
        } catch (IOException e) {
            Log.info("Could not delete " + queue);
        }
    }
}

From source file:info.pancancer.arch3.utils.Utilities.java

License:Open Source License

public static Channel setupQueue(HierarchicalINIConfiguration settings, String queue)
        throws IOException, TimeoutException {

    String server = settings.getString(Constants.RABBIT_HOST);
    String user = settings.getString(Constants.RABBIT_USERNAME);
    String pass = settings.getString(Constants.RABBIT_PASSWORD);

    Channel channel = null;

    try {/*from w ww  .j a  v  a 2  s . c o m*/

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(server);
        factory.setUsername(user);
        factory.setPassword(pass);
        factory.setAutomaticRecoveryEnabled(true);
        Connection connection = factory.newConnection();
        channel = connection.createChannel();
        channel.basicQos(1);
        channel.queueDeclare(queue, true, false, false, null);
        channel.confirmSelect();
        // channel.queueDeclarePassive(queue);

    } catch (IOException | TimeoutException ex) {
        // Logger.getLogger(Master.class.getName()).log(Level.SEVERE, null, ex);
        LOG.error("Error setting up queue connections to queue:" + queue + " on host: " + server
                + "; error is: " + ex.getMessage(), ex);
    }
    return channel;

}

From source file:javarpc_server.JavaRPC_Server.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException/*from www  .  j av a 2  s .  co m*/
 * @throws java.lang.InterruptedException
 */
public static void main(String[] args) throws IOException, InterruptedException {
    // TODO code application logic here

    ConnectionFactory factory = new ConnectionFactory();
    System.out.println(factory.getUsername() + " " + factory.getPassword());
    factory.setHost("localhost");

    Connection connection = factory.newConnection();
    Channel 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) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();

        BasicProperties props = delivery.getProperties();
        BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId())
                .build();

        String message = new String(delivery.getBody());

        System.out.println(" [.] convert(" + message + ")");
        String response = "" + convert(message);

        channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes());

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

From source file:mapas.Mapas.java

public static void main(String[] args) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setPassword("test");
    factory.setUsername("test");
    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//from w ww . j av  a2 s .c om
        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);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            System.out.println(" [x] Done");
            channel.basicAck(envelope.getDeliveryTag(), false);

        }
    };
    channel.basicConsume(TASK_QUEUE_NAME, false, consumer);
}

From source file:ms.dew.core.cluster.spi.rabbit.RabbitClusterMQ.java

License:Apache License

/**
 * MQ ??  ./*from ww  w .  j  a va  2 s .co m*/
 * <p>
 * exchange = fanout
 * ??
 *
 * @param topic    
 * @param consumer ?
 */
@Override
protected void doSubscribe(String topic, Consumer<String> consumer) {
    Channel channel = rabbitAdapter.getConnection().createChannel(false);
    try {
        channel.exchangeDeclare(topic, BuiltinExchangeType.FANOUT, true);
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, topic, "");
        channel.basicQos(1);
        channel.basicConsume(queueName, false,
                getDefaultConsumer(channel, topic, topic, "", queueName, consumer));
    } catch (IOException e) {
        logger.error("[MQ] Rabbit response error.", e);
    }
}

From source file:ms.dew.core.cluster.spi.rabbit.RabbitClusterMQ.java

License:Apache License

/**
 * MQ ??  ./*w  w w . ja v a2s  .co  m*/
 * <p>
 * exchange = topic
 * ??
 *
 * @param topic      
 * @param routingKey Key
 * @param queueName  ??
 * @param consumer   ?
 */
public void subscribeWithTopic(String topic, String routingKey, String queueName, Consumer<String> consumer) {
    Channel channel = rabbitAdapter.getConnection().createChannel(false);
    try {
        channel.queueDeclare(queueName, true, false, false, null);
        channel.exchangeDeclare(topic, BuiltinExchangeType.TOPIC, true);
        channel.queueBind(queueName, topic, routingKey);
        channel.basicQos(1);
        channel.basicConsume(queueName, false,
                getDefaultConsumer(channel, topic, topic, routingKey, queueName, consumer));
    } catch (IOException e) {
        logger.error("[MQ] Rabbit subscribeWithTopic error.", e);
    }
}

From source file:ms.dew.core.cluster.spi.rabbit.RabbitClusterMQ.java

License:Apache License

@Override
protected void doResponse(String address, Consumer<String> consumer) {
    Channel channel = rabbitAdapter.getConnection().createChannel(false);
    try {//w w w.j a  v a2s  . com
        channel.queueDeclare(address, true, false, false, null);
        channel.basicQos(1);
        channel.basicConsume(address, false,
                getDefaultConsumer(channel, address, "", address, address, consumer));
    } catch (IOException e) {
        logger.error("[MQ] Rabbit response error.", e);
    }
}

From source file:mx.bigdata.utils.amqp.AMQPClientHelperImpl.java

License:Apache License

public Channel declareChannel(ConnectionFactory factory, String key) throws Exception {
    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();
    Integer basicQos = conf.getInteger("channel_basic_qos");
    if (basicQos != null) {
        channel.basicQos(basicQos);
    } else {//from w ww  .j  ava  2 s  . c om
        channel.basicQos(DEFAULT_QOS);
    }
    channel.exchangeDeclare(getExchangeName(key), getExchangeType(key), true);
    return channel;
}

From source file:net.echinopsii.ariane.community.messaging.rabbitmq.ServiceFactory.java

License:Open Source License

/**
 * Create a message group request service.
 *
 * @param source the source where request are coming from
 * @param requestWorker the application request worker
 * @return the new message group request service
 *//*from   ww  w.java 2 s.  co m*/
@Override
public MomAkkaService msgGroupRequestService(String source, AppMsgWorker requestWorker) {
    final Connection connection = ((Client) super.getMomClient()).getConnection();
    MomAkkaService ret = null;
    ActorRef requestActor;
    MomConsumer consumer;
    MomMsgGroupServiceMgr msgGroupMgr;

    if (connection != null && connection.isOpen()) {
        try {
            Channel channel = connection.createChannel();
            channel.basicQos(1);
            requestActor = ServiceFactory.createRequestRouter(source, super.getMomClient(), channel,
                    requestWorker, null, true);
            consumer = ServiceFactory.createConsumer(source, channel, requestActor,
                    super.getMomClient().isMsgDebugOnTimeout());
            msgGroupMgr = ServiceFactory.createMsgGroupServiceManager(source, channel, requestWorker,
                    super.getMomClient());
            consumer.start();
            ret = new MomAkkaService().setMsgWorker(requestActor).setConsumer(consumer)
                    .setClient(super.getMomClient()).setMsgGroupServiceMgr(msgGroupMgr);
            super.getServices().add(ret);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return ret;
}