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:com.shopwiki.roger.rpc.BasicWorkerFactory.java

License:Apache License

@Override
public RpcWorkers createWorkers(String queuePrefix) throws IOException {
    Connection conn = null;/*  w  w w .j av  a2  s. c o  m*/
    try {
        conn = connector.getConnection(numThreads);

        List<Channel> channels = new ArrayList<Channel>();
        for (int i = 0; i < numThreads; i++) {
            Channel channel = conn.createChannel();
            channel.basicQos(1);
            channels.add(channel);
        }

        RpcWorkers workers = new RpcWorkers(conn);

        for (String procedureName : nameToHandler.keySet()) {
            RequestHandler<?, ?> handler = nameToHandler.get(procedureName);
            RpcWorker worker = new RpcWorker(handler, channels, queuePrefix, procedureName);
            workers.add(worker);
        }

        return workers;
        // TODO: Figure out a way to do this Exception handling outside of here ???
    } catch (IOException e) {
        RabbitConnector.closeConnection(conn);
        throw e;
    } catch (RuntimeException e) {
        RabbitConnector.closeConnection(conn);
        throw e;
    } catch (Error e) {
        RabbitConnector.closeConnection(conn);
        throw e;
    }
}

From source file:com.wss.qvh.log.ConsumerThread.java

public void consumer() throws IOException, TimeoutException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(Constant.RABBITMQ_USERNAME);
    factory.setPassword(Constant.RABBITMQ_PASSWORD);
    factory.setVirtualHost(Constant.RABBITMQ_VIRTUAL_HOST);
    factory.setRequestedChannelMax(Constant.NUM_PRODUCER);
    factory.setHost(Constant.RABBITMQ_HOST);

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

    channel.queueDeclare(Constant.QUEUE_NAME, Constant.QUEUE_DURABLE, false, false, null);
    channel.basicQos(Constant.QUEUE_PREFETCH);
    QueueingConsumer consumer = new QueueingConsumer(channel);
    boolean autoAck = false;
    channel.basicConsume(Constant.QUEUE_NAME, autoAck, consumer);

    while (true) {
        QueueingConsumer.Delivery delivery;
        try {/*from ww  w.  j  ava 2  s  .  c o m*/
            delivery = consumer.nextDelivery();
        } catch (InterruptedException | ShutdownSignalException | ConsumerCancelledException ex) {
            logger.warn(ex.getMessage(), ex);
            try {
                Thread.sleep(100L);
            } catch (InterruptedException ex1) {
                logger.warn(ex1.getMessage(), ex1);
            }
            continue;
        }

        String message;
        try {
            message = getMessenge(delivery);
        } catch (InterruptedException ex) {
            logger.warn(ex.getMessage(), ex);
            try {
                Thread.sleep(100L);
            } catch (InterruptedException ex1) {
                logger.warn(ex1.getMessage(), ex1);
            }
            continue;
        }
        if (message == null || message.isEmpty()) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
                logger.warn(ex.getMessage(), ex);
            }
        } else {
            LogObject lo = new LogObject();
            try {
                lo.parseJson(message);
                store(lo);
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            } catch (Exception ex) {
                logger.debug(message, ex);
            }
        }
    }
}

From source file:cs.rsa.ts14dist.appserver.RabbitMQDaemon.java

License:Apache License

@Override
public void run() {

    Connection connection = null;
    Channel channel = null;
    try {/*from   w w w . j  a  v a  2s .c  om*/
        ConnectionFactory factory = new ConnectionFactory();
        logger.info("Starting RabbitMQDaemon, MQ IP = " + hostname);
        factory.setHost(hostname);

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

        channel.queueDeclare(rpcQueueName, false, false, false, null);

        channel.basicQos(1);

        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(rpcQueueName, false, consumer);

        while (true) {
            String response = null;

            // Block and fetch next msg from queue
            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");
                logger.trace("Received msg: " + message);

                // Convert the message to a JSON request object
                JSONObject request = (JSONObject) JSONValue.parse(message);

                // Delegate to the server request handler for handling the
                // request and computing an answer
                JSONObject reply = serverRequestHandler.handleRequest(request);

                // Convert the answer back into a string for replying to
                // client
                response = reply.toJSONString();
            } catch (Exception e) {
                logger.error(" Exception in MQDAemon run()/while true] " + e.toString());
                response = "wrong";
            } finally {
                logger.trace("Returning answer: " + response);
                channel.basicPublish("", props.getReplyTo(), replyProps, response.getBytes("UTF-8"));
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                logger.trace("Answer acknowledged.");
            }
        }
    } catch (Exception e) {
        logger.error("Exception in daemon's outer loop: nested exception" + e.getMessage());
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ignore) {
            }
        }
    }
}

From source file:dfki.sb.rabbitmqjava.RabbitMQObjectStreamServer.java

License:Open Source License

public static void main(String[] argv) {
    Channel channel = null;
    try {//  w w w  . ja v a 2 s .  co m
        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("Starting server waiting for client requests:");
        processSendAndRecivePackets(consumer, channel);
        if (argv != null && argv.length > 0 && argv[0].equalsIgnoreCase("infinite")) {
            while (true) {
                System.out.println("Waiting for next client");
                processSendAndRecivePackets(consumer, channel);
            }
        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException ignore) {
            }
        }
    }
}

From source file:dfki.sb.rabbitmqjava.RabbitMQServer.java

License:Open Source License

public static void main(String[] argv) {
    Connection connection = null;
    Channel channel = null;
    try {//from   w w  w.  j  a  va 2s .  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("Starting server waiting for client requests:");
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            BasicProperties props = delivery.getProperties();
            BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId())
                    .build();
            DataInputStream dis = new DataInputStream(
                    new BufferedInputStream(new ByteArrayInputStream(delivery.getBody())));
            try {
                int type = dis.readInt();
                byte[] response;
                if (type == 2) {
                    response = handleMarketRequest(dis);
                } else {
                    response = handleQuoteRequest(dis);
                }
                channel.basicPublish("", props.getReplyTo(), replyProps, response);
                dis.close();
            } catch (IOException | ClassNotFoundException e) {
                System.out.println(" [.] " + e.toString());
            } finally {
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        }
    } catch (IOException | InterruptedException | ShutdownSignalException | ConsumerCancelledException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException ignore) {
            }
        }
    }
}

From source file:es.devcircus.rabbitmq_examples.rabbitmq_rpc.RPCServer.java

License:Open Source License

/**
 *
 * @param argv// w  ww.java 2 s  .  co m
 */
public static void main(String[] argv) {
    Connection connection = null;
    Channel channel = null;
    try {
        ConnectionFactory factory = new ConnectionFactory();
        //            factory.setHost("localhost");
        factory.setHost("192.168.0.202");
        //            factory.setPort(5671);

        //            factory.useSslProtocol();

        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 (IOException | InterruptedException | ShutdownSignalException | ConsumerCancelledException e) {
        System.out.println(e.toString());
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ignore) {
            }
        }
    }
}

From source file:es.devcircus.rabbitmq_examples.rabbitmq_work_queues.Worker.java

License:Open Source License

/**
 * //  w w w.  j  a v a 2s. c  o m
 * @param argv
 * @throws Exception 
 */
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(TASK_QUEUE_NAME, true, false, false, null);
    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

    channel.basicQos(1);

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(TASK_QUEUE_NAME, false, consumer);

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

        System.out.println(" [x] Received '" + message + "'");
        doWork(message);
        System.out.println(" [x] Done");

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

From source file:gash.router.server.MessageServer.java

License:Apache License

public void createQueue() throws IOException, ShutdownSignalException, ConsumerCancelledException,
        InterruptedException, SQLException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.queueDeclare("inbound_queue", false, false, false, null);
    channel.basicQos(1);
    postgre = new PostgreSQL(url, username, password, dbname, ssl);
    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume("inbound_queue", false, consumer);
    //       Map<String, byte[]> map = new HashMap<String, byte[]>();
    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        BasicProperties props = delivery.getProperties();
        String request = props.getType();
        System.out.println(request);

        if (request != null) {
            if (request.equals("get")) {
                String key = new String(delivery.getBody());
                BasicProperties replyProps = new BasicProperties.Builder()
                        .correlationId(props.getCorrelationId()).build();
                byte[] image = postgre.get(key);
                channel.basicPublish("", props.getReplyTo(), replyProps, image);
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }// w  ww.  ja  v  a  2  s.c o  m

            if (request.equals("put")) {
                byte[] image = delivery.getBody();
                postgre.put(props.getUserId(), image);
                BasicProperties replyProps = new BasicProperties.Builder()
                        .correlationId(props.getCorrelationId()).build();

                channel.basicPublish("", props.getReplyTo(), replyProps, image);
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
            if (request.equals("post")) {
                System.out.println("Message Server");
                String key = postgre.post(delivery.getBody());
                BasicProperties replyProps = new BasicProperties.Builder()
                        .correlationId(props.getCorrelationId()).build();

                channel.basicPublish("", props.getReplyTo(), replyProps, key.getBytes());
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
            if (request.equals("delete")) {
                String key = new String(delivery.getBody());
                postgre.delete(key);
            }

        }
    }
}

From source file:in.cs654.chariot.ashva.AshvaServer.java

License:Open Source License

public static void main(String[] args) {
    Connection connection = null;
    Channel channel;
    try {/*from   w ww . ja  v  a  2  s  . co  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("Ashva Server started. Waiting for requests...");

        AshvaHelper.joinOrStartChariotPool();
        AshvaHelper.startHeartbeat();

        while (true) {
            final QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            BasicResponse response = new BasicResponse();
            BasicRequest request = new BasicRequest();
            final BasicProperties props = delivery.getProperties();
            final BasicProperties replyProps = new 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 = AshvaProcessor.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();
                LOGGER.info("Responding to request id " + request.getRequestId() + " " + response.getStatus());
                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:in.cs654.chariot.prashti.PrashtiServer.java

License:Open Source License

public static void main(String[] args) {
    Connection connection = null;
    Channel channel;
    try {/*www  .  j  av a 2 s.  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("Prashti Server started. Waiting for requests...");

        final List<Prashti> prashtiList = D2Client.getOnlinePrashtiServers();
        final String ipAddr = CommonUtils.getIPAddress();
        prashtiList.add(new Prashti(ipAddr));
        LOGGER.info("Notifying D2 to set Prashti Server IP Address");
        D2Client.setPrashtiServers(prashtiList);

        while (true) {
            final QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            BasicResponse response = new BasicResponse();
            BasicRequest request = new BasicRequest();
            final BasicProperties props = delivery.getProperties();
            final BasicProperties replyProps = new 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 = RequestProcessor.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();
                LOGGER.info("Responding to request id " + request.getRequestId() + " " + response.getStatus());
                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) {
            }
        }
    }
}