List of usage examples for com.rabbitmq.client Channel basicQos
void basicQos(int prefetchCount) throws IOException;
From source file:net.echinopsii.ariane.community.messaging.rabbitmq.ServiceFactory.java
License:Open Source License
/** * Create a request service (can not handle message grouping) * * @param source the source where request are coming from * @param requestWorker the application request worker * @return the new request service//from w w w .ja v a 2 s . com */ @Override public MomAkkaService requestService(final String source, final AppMsgWorker requestWorker) { final Connection connection = ((Client) super.getMomClient()).getConnection(); MomAkkaService ret = null; ActorRef requestActor; MomConsumer consumer; if (connection != null && connection.isOpen()) { try { Channel channel = connection.createChannel(); channel.basicQos(1); requestActor = ServiceFactory.createRequestRouter(source, super.getMomClient(), channel, requestWorker, null, false); consumer = ServiceFactory.createConsumer(source, channel, requestActor, super.getMomClient().isMsgDebugOnTimeout()); consumer.start(); ret = new MomAkkaService().setMsgWorker(requestActor).setConsumer(consumer) .setClient(super.getMomClient()); super.getServices().add(ret); } catch (IOException e) { e.printStackTrace(); } } return ret; }
From source file:org.apache.airavata.datacat.agent.messageBroker.AiravataUpdateListener.java
License:Apache License
public void startBroker() { (new Thread(new Runnable() { @Override/* w ww. j a v a 2 s. co m*/ public void run() { try { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(RABBITMQ_HOST); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(EXCHANGE_NAME, "topic"); String queueName = channel.queueDeclare().getQueue(); channel.basicQos(1); channel.queueBind(queueName, EXCHANGE_NAME, BINDING_KEY); logger.debug("Waiting for messages. To exit press CTRL+C"); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); while (runFileUpdateListener) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); Message message = new Message(); ThriftUtils.createThriftFromBytes(delivery.getBody(), message); TBase event = null; if (message.getMessageType().equals(MessageType.EXPERIMENT_OUTPUT)) { ExperimentOutputCreatedEvent experimentOutputCreatedEvent = new ExperimentOutputCreatedEvent(); ThriftUtils.createThriftFromBytes(message.getEvent(), experimentOutputCreatedEvent); logger.debug(" Message Received with message id '" + message.getMessageId() + "' and with message type '" + message.getMessageType() + "' with experiment name " + experimentOutputCreatedEvent.getExperimentName()); event = experimentOutputCreatedEvent; logger.debug(" [x] Received FileInfo Message'"); process(experimentOutputCreatedEvent, message.getUpdatedTime()); logger.debug(" [x] Done Processing FileInfo Message"); } else { logger.debug("Recieved message of type ..." + message.getMessageType()); } } } catch (Exception e) { logger.error(e); } } })).start(); }
From source file:org.apache.flume.amqp.AmqpConsumer.java
License:Apache License
/** * This method declares the exchange, queue and bindings needed by this consumer. * The method returns the queue name that will be used by this consumer. * * @param channel channel used to issue AMQP commands * @return queue that will have messages consumed from * @throws IOException thrown if there is any communication exception *//* w ww .j a va 2 s.c o m*/ @VisibleForTesting protected String declarationsForChannel(Channel channel) throws IOException { // setup exchange, queue and binding if (prefetchSize > 0) { channel.basicQos(prefetchSize); } // if exchange is provided if (exchangeName != null) { channel.exchangeDeclare(exchangeName, exchangeType, durableExchange); // named queue or server generated if (queueName == null) { queueName = channel.queueDeclare().getQueue(); } else { channel.queueDeclare(queueName, durableQueue, exclusiveQueue, autoDeleteQueue, null); } if (bindings.length > 0) { // multiple bindings for (String binding : bindings) { channel.queueBind(queueName, exchangeName, binding); } } else { // no binding given - this could be the case if it is a fanout exchange channel.queueBind(queueName, exchangeName, Constants.AMQP.SERVER_GENERATED_QUEUE_NAME); } } return queueName; }
From source file:org.apache.niolex.rabbit.rpc.RPCServer.java
License:Apache License
public static void main(String[] argv) { Connection connection = null; Channel channel = null; try {//from w w w . ja va 2 s.c o 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(" [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:org.apache.synapse.transport.amqp.connectionfactory.AMQPTransportConnectionFactory.java
License:Apache License
private Channel createChannel(Connection connection, Map<String, String> parameters) throws IOException { Channel ch; if (parameters.get(AMQPTransportConstant.PARAMETER_AMQP_CHANNEL_NUMBER) != null) { int index = 0; try {/*from w ww . j ava 2 s. c om*/ index = Integer.parseInt(parameters.get(AMQPTransportConstant.PARAMETER_AMQP_CHANNEL_NUMBER)); } catch (NumberFormatException e) { index = 1; // assume default, // fair dispatch see http://www.rabbitmq.com/tutorials/tutorial-two-java.html } ch = connection.createChannel(index); } else { ch = connection.createChannel(); } int prefetchSize = 1024; if (parameters.get(AMQPTransportConstant.PARAMETER_CHANNEL_PREFETCH_SIZE) != null) { try { prefetchSize = Integer .parseInt(parameters.get(AMQPTransportConstant.PARAMETER_CHANNEL_PREFETCH_SIZE)); } catch (NumberFormatException e) { prefetchSize = 1024; // assume default } } int prefetchCount = 0; if (parameters.get(AMQPTransportConstant.PARAMETER_CHANNEL_PREFETCH_COUNT) != null) { try { prefetchCount = Integer .parseInt(parameters.get(AMQPTransportConstant.PARAMETER_CHANNEL_PREFETCH_COUNT)); ch.basicQos(prefetchCount); } catch (NumberFormatException e) { prefetchCount = 0; // assume default } } boolean useGlobally = false; if (parameters.get(AMQPTransportConstant.PARAMETER_CHANNEL_QOS_GLOBAL) != null) { useGlobally = Boolean.parseBoolean(parameters.get(AMQPTransportConstant.PARAMETER_CHANNEL_QOS_GLOBAL)); } return ch; }
From source file:org.hobbit.core.rabbit.EchoServer.java
License:Open Source License
@Override public void run() { running = true;//w w w . j ava2 s .co m Connection connection = null; try { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(rabbitHost); connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.basicQos(1); channel.queueDeclare(queueName, false, false, true, null); Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { BasicProperties replyProps = new BasicProperties.Builder() .correlationId(properties.getCorrelationId()).deliveryMode(2).build(); channel.basicPublish("", properties.getReplyTo(), replyProps, body); } }; channel.basicConsume(queueName, true, consumer); while (running) { Thread.sleep(3000); } } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (IOException e) { } } } }
From source file:org.mazerunner.core.messaging.Worker.java
License:Apache License
public void doMain(String[] args) throws Exception { CmdLineParser parser = new CmdLineParser(this); // if you have a wider console, you could increase the value; // here 80 is also the default parser.setUsageWidth(80);/* w w w . ja va 2 s . c o m*/ try { // parse the arguments. parser.parseArgument(args); if (sparkMaster == "" || hadoopHdfs == "") throw new CmdLineException(parser, "Options required: --hadoop.hdfs <url>, --spark.master <url>"); ConfigurationLoader.getInstance().setHadoopHdfsUri(hadoopHdfs); ConfigurationLoader.getInstance().setSparkHost(sparkMaster); ConfigurationLoader.getInstance().setAppName(sparkAppName); ConfigurationLoader.getInstance().setExecutorMemory(sparkExecutorMemory); ConfigurationLoader.getInstance().setDriverHost(driverHost); ConfigurationLoader.getInstance().setRabbitmqNodename(rabbitMqHost); } catch (CmdLineException e) { // if there's a problem in the command line, // you'll get this exception. this will report // an error message. System.err.println(e.getMessage()); System.err.println("java -cp $CLASSPATH [<spark-config-options>] <main-class> [<mazerunner-args>]"); // print the list of available options parser.printUsage(System.err); System.err.println(); // print option sample. This is useful some time System.err.println(" Example: java -cp $CLASSPATH org.mazerunner.core.messaging.Worker" + parser.printExample(ALL)); return; } ConnectionFactory factory = new ConnectionFactory(); factory.setHost(ConfigurationLoader.getInstance().getRabbitmqNodename()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null); channel.basicQos(20); // Initialize spark context GraphProcessor.initializeSparkContext(); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(TASK_QUEUE_NAME, false, consumer); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); System.out.println(" [x] Received '" + message + "'"); // Deserialize message Gson gson = new Gson(); ProcessorMessage processorMessage = gson.fromJson(message, ProcessorMessage.class); // Run PageRank GraphProcessor.processEdgeList(processorMessage); System.out.println(" [x] Done '" + message + "'"); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } }
From source file:org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer.java
License:Apache License
private void doConsumeFromQueue(String queue) { if (!isActive()) { if (this.logger.isDebugEnabled()) { this.logger.debug("Consume from queue " + queue + " ignore, container stopping"); }/*from www . j a v a 2 s .co m*/ return; } Connection connection = null; // NOSONAR (close) try { connection = getConnectionFactory().createConnection(); } catch (Exception e) { this.consumersToRestart.add(new SimpleConsumer(null, null, queue)); throw new AmqpConnectException(e); } Channel channel = null; SimpleConsumer consumer = null; try { channel = connection.createChannel(isChannelTransacted()); channel.basicQos(getPrefetchCount()); consumer = new SimpleConsumer(connection, channel, queue); channel.queueDeclarePassive(queue); consumer.consumerTag = channel.basicConsume(queue, getAcknowledgeMode().isAutoAck(), (getConsumerTagStrategy() != null ? getConsumerTagStrategy().createConsumerTag(queue) : ""), false, isExclusive(), getConsumerArguments(), consumer); } catch (IOException e) { RabbitUtils.closeChannel(channel); RabbitUtils.closeConnection(connection); if (e.getCause() instanceof ShutdownSignalException && e.getCause().getMessage().contains("in exclusive use")) { getExclusiveConsumerExceptionLogger().log(logger, "Exclusive consumer failure", e.getCause()); publishConsumerFailedEvent("Consumer raised exception, attempting restart", false, e); } else if (this.logger.isDebugEnabled()) { this.logger.debug("Queue not present or basicConsume failed, scheduling consumer " + consumer + " for restart"); } this.consumersToRestart.add(consumer); consumer = null; } synchronized (this.consumersMonitor) { if (consumer != null) { this.cancellationLock.add(consumer); this.consumers.add(consumer); this.consumersByQueue.add(queue, consumer); if (this.logger.isInfoEnabled()) { this.logger.info(consumer + " started"); } } } }
From source file:org.springframework.amqp.rabbit.MulticastMain.java
License:Mozilla Public License
public static void main(String[] args) { Options options = getOptions();//from ww w . j a v a 2 s . c o m CommandLineParser parser = new GnuParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('?')) { usage(options); System.exit(0); } String hostName = strArg(cmd, 'h', "localhost"); int portNumber = intArg(cmd, 'p', AMQP.PROTOCOL.PORT); String exchangeType = strArg(cmd, 't', "direct"); String exchangeName = strArg(cmd, 'e', exchangeType); int samplingInterval = intArg(cmd, 'i', 1); int rateLimit = intArg(cmd, 'r', 0); int producerCount = intArg(cmd, 'x', 1); int messageCount = intArg(cmd, 'N', 0); int consumerCount = intArg(cmd, 'y', 1); int connectionCount = cmd.hasOption('c') ? 1 : consumerCount; int producerTxSize = intArg(cmd, 'm', 0); int consumerTxSize = intArg(cmd, 'n', 0); boolean autoAck = cmd.hasOption('a'); int prefetchCount = intArg(cmd, 'q', 0); int minMsgSize = intArg(cmd, 's', 0); int timeLimit = intArg(cmd, 'z', 0); List<String> flags = lstArg(cmd, 'f'); int frameMax = intArg(cmd, 'M', 0); int heartbeat = intArg(cmd, 'b', 0); // setup String id = UUID.randomUUID().toString(); Stats stats = new Stats(1000L * samplingInterval); ConnectionFactory factory = new ConnectionFactory(); factory.setHost(hostName); factory.setPort(portNumber); factory.setRequestedFrameMax(frameMax); factory.setRequestedHeartbeat(heartbeat); Connection[] consumerConnections = new Connection[connectionCount]; for (int i = 0; i < connectionCount; i++) { Connection conn = factory.newConnection(); consumerConnections[i] = conn; } Thread[] consumerThreads = new Thread[consumerCount]; for (int i = 0; i < consumerCount; i++) { System.out.println("starting consumer #" + i); Connection conn = consumerConnections[i % connectionCount]; Channel channel = conn.createChannel(); if (consumerTxSize > 0) channel.txSelect(); channel.exchangeDeclare(exchangeName, exchangeType); String queueName = channel.queueDeclare("", flags.contains("persistent"), true, false, null) .getQueue(); QueueingConsumer consumer = new QueueingConsumer(channel); if (prefetchCount > 0) channel.basicQos(prefetchCount); channel.basicConsume(queueName, autoAck, consumer); channel.queueBind(queueName, exchangeName, id); Thread t = new Thread(new Consumer(consumer, id, consumerTxSize, autoAck, stats, timeLimit)); consumerThreads[i] = t; t.start(); } Thread[] producerThreads = new Thread[producerCount]; Connection[] producerConnections = new Connection[producerCount]; for (int i = 0; i < producerCount; i++) { System.out.println("starting producer #" + i); Connection conn = factory.newConnection(); producerConnections[i] = conn; Channel channel = conn.createChannel(); if (producerTxSize > 0) channel.txSelect(); channel.exchangeDeclare(exchangeName, exchangeType); final Producer p = new Producer(channel, exchangeName, id, flags, producerTxSize, 1000L * samplingInterval, rateLimit, minMsgSize, timeLimit, messageCount); channel.addReturnListener(p); Thread t = new Thread(p); producerThreads[i] = t; t.start(); } for (int i = 0; i < producerCount; i++) { producerThreads[i].join(); producerConnections[i].close(); } for (int i = 0; i < consumerCount; i++) { consumerThreads[i].join(); } for (int i = 0; i < connectionCount; i++) { consumerConnections[i].close(); } } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); usage(options); } catch (Exception e) { System.err.println("Main thread caught exception: " + e); e.printStackTrace(); System.exit(1); } }
From source file:org.teksme.server.queue.consumer.impl.ChannelTracker.java
License:Apache License
@SuppressWarnings({ "rawtypes", "unchecked" }) @Override/*from ww w .j a v a2 s .c o m*/ public Map<Channel, String> addingService(ServiceReference reference) { Connection conn = (Connection) context.getService(reference); String consumerTag = null; Map<Channel, String> registry = new HashMap<Channel, String>(); Channel channel = null; try { XmlConfiguration read = new XmlConfiguration(); TeksConfig.MessageMiddleware config = read.readMessageMiddlewareConfig("teks-server.xml"); String queueName = null; List<MessageMiddleware.Queue> queues = config.getQueues(); for (Queue queue : queues) { queueName = queue.getName(); logger.info("Declaring basic MQ consumer for queue: " + queueName); channel = conn.createChannel(); // ensure you never have more than 100 messages queued up in the // consumer channel.basicQos(100); Class consumerClazz; consumerClazz = Class.forName(queue.getConsumerClass()); Constructor constructor = consumerClazz.getConstructor(Channel.class); BaseConsumer consumer = (BaseConsumer) constructor.newInstance(channel); // OutboundMessageConsumer consumer = new // OutboundMessageConsumer(channel); consumer.addMessageListener(new OutboundSMSHandler()); consumerTag = channel.basicConsume(queueName, consumer); registry.put(channel, consumerTag); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); return null; } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return registry; }