List of usage examples for com.rabbitmq.client Channel basicQos
void basicQos(int prefetchCount) throws IOException;
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) * /*from w ww .j a va 2 s.c om*/ * @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:play.modules.rabbitmq.RabbitMQPlugin.java
License:Apache License
/** * Creates the channel to publish messages to an exchange * (Exchange is created. Queue and bindings are NOT created) * /* w ww. j a va 2s. c o m*/ * @param exchangeName * the exchange name * @return the channel * @throws Exception * the exception */ public Channel createPublishersChannel(String exchangeName) 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); // 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:reactor.rabbitmq.Receiver.java
License:Open Source License
public Flux<AcknowledgableDelivery> consumeManuelAck(final String queue, ReceiverOptions options) { // TODO track flux so it can be disposed when the sender is closed? // could be also developer responsibility return Flux.create(emitter -> { connectionMono.subscribe(connection -> { try { Channel channel = connection.createChannel(); if (options.getQos() != 0) { channel.basicQos(options.getQos()); }/*w w w. j a v a 2 s.com*/ final DefaultConsumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { AcknowledgableDelivery message = new AcknowledgableDelivery(envelope, properties, body, getChannel()); if (options.getHookBeforeEmit().apply(emitter, message)) { emitter.next(message); } } }; final String consumerTag = channel.basicConsume(queue, false, consumer); emitter.onDispose(() -> { try { if (channel.isOpen() && channel.getConnection().isOpen()) { channel.basicCancel(consumerTag); channel.close(); } } catch (TimeoutException | IOException e) { throw new ReactorRabbitMqException(e); } }); } catch (IOException e) { throw new ReactorRabbitMqException(e); } }); }, options.getOverflowStrategy()); }
From source file:se.kodiak.logging.appenders.util.MQListener.java
License:Open Source License
public MQListener() { try {//from ww w . ja v a2 s. c o m ConnectionFactory factory = new ConnectionFactory(); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.basicQos(1); channel.exchangeDeclare("test", "topic"); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, "test", "log.*"); consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:taucalcmanager.TaucalcManager.java
/** * @param args the command line arguments * @throws java.io.IOException//from w w w . j av a2 s.c om * @throws java.util.concurrent.TimeoutException */ public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(WORKQUEUENAME, false, false, false, null); channel.queueDeclare(RESULTQUEUENAME, false, false, false, null); channel.basicQos(1); int calcs = Integer.parseInt(args[0]); int triesPerCalc = Integer.parseInt(args[1]); int[] results = new int[calcs]; byte[] task = { (byte) (triesPerCalc >> 24), (byte) (triesPerCalc >> 16), (byte) (triesPerCalc >> 8), (byte) (triesPerCalc) }; System.out.println("Start Publishing"); for (int i = 0; i < calcs; i++) { channel.basicPublish("", WORKQUEUENAME, null, task); } System.out.println("Done Publishing"); GetResponse response; System.out.println("Start Gathering results"); for (int i = 0; i < calcs; i++) { System.out.println("Waiting for next result: ( " + i + " )"); do { response = channel.basicGet(RESULTQUEUENAME, true); } while (response == null); results[i] = ByteBuffer.wrap(response.getBody()).getInt(); System.out.println("Received result: " + results[i]); } System.out.println("Done gathering results"); System.out.println("Calculating tau"); BigDecimal result = sumToTau(sum(results), calcs, triesPerCalc); System.out.println("Tau = " + result); BigDecimal two = new BigDecimal(2); System.out.println("pi = tau/2 = " + result.divide(two, RoundingMode.HALF_UP)); channel.close(); connection.close(); }
From source file:taucalcworker.TaucalcWorker.java
/** * @param args the command line arguments * @throws java.io.IOException//from w w w . java 2s. c om * @throws java.util.concurrent.TimeoutException */ public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(WORKQUEUENAME, false, false, false, null); channel.queueDeclare(RESULTQUEUENAME, false, false, false, null); channel.basicQos(1); byte[] inputbyte = { 0, 0, 0, 0 }; String input = ""; do { if (System.in.available() > 0) { System.in.read(inputbyte); input = new String(inputbyte); } GetResponse response = channel.basicGet(WORKQUEUENAME, false); if (response != null) { long deliverytag = response.getEnvelope().getDeliveryTag(); byte[] body = response.getBody(); int tries = ByteBuffer.wrap(body).getInt(); System.out.println("Task received: " + tries); int success = 0; for (int i = 0; i < tries; i++) { double x = Math.random(); double y = Math.random(); if (x * x + y * y <= 1) { success++; } } System.out.println("success: " + success + " out of " + tries); double tau = ((double) success / tries) * 8; System.out.println("Tau = " + tau); byte[] resultbytes = new byte[8]; ByteBuffer.wrap(resultbytes).putDouble(tau); channel.basicPublish("", RESULTQUEUENAME, null, resultbytes); channel.basicAck(deliverytag, false); } } while (!input.equals("stop")); channel.close(); connection.close(); System.out.println("You stopped the program."); }
From source file:vn.com.uet.performance.rabbitmq.MulticastParams.java
License:Open Source License
public Consumer createConsumer(Connection connection, Stats stats, String id) throws IOException { Channel channel = connection.createChannel(); if (consumerTxSize > 0) channel.txSelect();/*w w w.j ava 2s. c o m*/ String qName = configureQueue(connection, id); if (consumerPrefetch > 0) channel.basicQos(consumerPrefetch); if (channelPrefetch > 0) channel.basicQos(channelPrefetch, true); return new Consumer(channel, id, qName, consumerTxSize, autoAck, multiAckEvery, stats, consumerRateLimit, consumerMsgCount, timeLimit); }
From source file:wiki.messaging.Receive.java
License:Open Source License
public static void main(String[] args) throws IOException, InterruptedException { String url = null;/*w w w .j a v a 2 s . c o m*/ String rabbitMqUrl = null; for (int i = 0; i < args.length; i++) { if (args[i].equals("ds")) { url = args[i + 1]; } else if (args[i].equals("rq")) { rabbitMqUrl = args[i + 1]; } else if (args[i].equals("mj")) { maxJobs = Integer.valueOf(args[i + 1]); } } if (rabbitMqUrl == null) { rabbitMqUrl = "192.168.1.108"; } if (url == null) { url = "localhost"; } // if (resultUrl == null) { // resultUrl = url; // } threadPool = new ExecutorCompletionService<>(Executors.newFixedThreadPool(maxJobs)); System.out.println("DataSource: " + url); // System.out.println("ResultWrite: " + resultUrl); DbConnector ds = new DbConnector(url); // DbConnector rs = new DbConnector(resultUrl); ConnectionFactory factory = new ConnectionFactory(); factory.setHost(rabbitMqUrl); factory.setUsername("wiki"); factory.setPassword("wiki"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); channel.queueDeclare(RESULT_QUEUE_NAME, true, false, false, null); System.out.println(" [*] Waiting for messages."); channel.basicQos(maxJobs); QueueingConsumer consumer = new QueueingConsumer(channel); boolean autoAck = false; channel.basicConsume(QUEUE_NAME, autoAck, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); System.out.println(" [x] Received '" + message + "'"); doWork(message, ds); saveResult(channel); System.out.println(" [x] Done"); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } }
From source file:wiki.messaging.Treeceive.java
License:Open Source License
public static void main(String[] args) throws IOException, InterruptedException { String url = null;//from w w w . j av a 2 s . co m String rabbitMqUrl = null; for (int i = 0; i < args.length; i++) { if (args[i].equals("ds")) { url = args[i + 1]; } else if (args[i].equals("rq")) { rabbitMqUrl = args[i + 1]; } else if (args[i].equals("mj")) { maxJobs = Integer.valueOf(args[i + 1]); } } if (rabbitMqUrl == null) { rabbitMqUrl = "192.168.1.108"; } if (url == null) { url = "localhost"; } // if (resultUrl == null) { // resultUrl = url; // } threadPool = new ExecutorCompletionService<>(Executors.newFixedThreadPool(maxJobs)); System.out.println("DataSource: " + url); // System.out.println("ResultWrite: " + resultUrl); DbConnector ds = new DbConnector(url); // DbConnector rs = new DbConnector(resultUrl); ConnectionFactory factory = new ConnectionFactory(); factory.setHost(rabbitMqUrl); factory.setUsername("wiki"); factory.setPassword("wiki"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); channel.queueDeclare(RESULT_QUEUE_NAME, true, false, false, null); System.out.println(" [*] Waiting for messages."); channel.basicQos(maxJobs); QueueingConsumer consumer = new QueueingConsumer(channel); boolean autoAck = false; channel.basicConsume(QUEUE_NAME, autoAck, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); System.out.println(" [x] Received '" + message + "'"); doWork(message, ds); saveResults(channel); System.out.println(" [x] Done"); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } }
From source file:workqueue.Worker.java
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("datdb.cphbusiness.dk"); 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 w w . ja v a 2 s. c o m 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); }