Java Code Examples for com.rabbitmq.client.Channel#basicQos()
The following examples show how to use
com.rabbitmq.client.Channel#basicQos() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClientReceive1.java From java-study with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws java.io.IOException,java.lang.InterruptedException, TimeoutException, KeyManagementException, NoSuchAlgorithmException, URISyntaxException{ ConnectionFactory factory=new ConnectionFactory(); // factory.setHost("localhost"); // factory.setVirtualHost("my_mq"); // factory.setUsername("zhxia"); // factory.setPassword("123456"); factory.setUri("amqp://guest:[email protected]:5672");//获取url Connection connection=factory.newConnection(); Channel channel=connection.createChannel(); channel.queueDeclare(queue_name, durable, false, false, null); System.out.println("Wait for message"); channel.basicQos(1); //消息分发处理 QueueingConsumer consumer=new QueueingConsumer(channel); channel.basicConsume(queue_name, autoAck, consumer); while(true){ Thread.sleep(500); QueueingConsumer.Delivery deliver=consumer.nextDelivery(); String message=new String(deliver.getBody()); System.out.println("Message received:"+message); channel.basicAck(deliver.getEnvelope().getDeliveryTag(), false); } }
Example 2
Source File: ProducerConsumer.java From util4j with Apache License 2.0 | 6 votes |
public void consumer2() throws Exception { //1、获取连接 Connection connection =RabbitMqConnectionFactoy.getConnection(); //2、声明通道 Channel channel = connection.createChannel(); //3、声明队列 channel.queueDeclare(QUEUE_NAME, false, false, false, null); //同一时刻服务器只会发送一条消息给消费者(如果设置为N,则当客户端堆积N条消息后服务端不会推送给客户端了) channel.basicQos(1);//每次只从服务器取1个处理 //4、定义队列的消费者 DeliverCallback deliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); System.out.println("-->消费者2号,收到消息,msg :"+message+",header:"+delivery.getProperties().getHeaders().toString()); channel.basicAck( delivery.getEnvelope().getDeliveryTag(), false); }; channel.basicConsume(QUEUE_NAME, autoAck, deliverCallback, consumerTag -> { }); }
Example 3
Source File: ProducerConsumer.java From util4j with Apache License 2.0 | 6 votes |
public void consumer3() throws Exception { //1、获取连接 Connection connection =RabbitMqConnectionFactoy.getConnection(); //2、声明通道 Channel channel = connection.createChannel(); //3、声明队列 channel.queueDeclare(QUEUE_NAME, false, false, false, null); //同一时刻服务器只会发送一条消息给消费者(如果设置为N,则当客户端堆积N条消息后服务端不会推送给客户端了) channel.basicQos(1);//每次只从服务器取1个处理 //4、定义队列的消费者 DeliverCallback deliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); System.out.println("-->消费者3号,收到消息,msg :"+message+",header:"+delivery.getProperties().getHeaders().toString()); channel.basicAck( delivery.getEnvelope().getDeliveryTag(), false); }; channel.basicConsume(QUEUE_NAME, autoAck, deliverCallback, consumerTag -> { }); }
Example 4
Source File: MessageSubscriberFactory.java From Insights with Apache License 2.0 | 6 votes |
public void registerSubscriber(String routingKey, final EngineSubscriberResponseHandler responseHandler) throws Exception { Channel channel = connection.createChannel(); String queueName = routingKey.replace(".", "_"); channel.queueDeclare(queueName, true, false, false, null); channel.queueBind(queueName, MessageConstants.EXCHANGE_NAME, routingKey); channel.basicQos(ApplicationConfigProvider.getInstance().getMessageQueue().getPrefetchCount()); responseHandler.setChannel(channel); log.debug("prefetchCount "+ApplicationConfigProvider.getInstance().getMessageQueue().getPrefetchCount() ); Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { responseHandler.handleDelivery(consumerTag, envelope, properties, body); } }; channel.basicConsume(queueName, false, routingKey, consumer); }
Example 5
Source File: AMQPReceiver.java From reactive with Creative Commons Zero v1.0 Universal | 6 votes |
public static void main(String[] args) throws Exception { Channel channel = AMQPCommon.connect(); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicQos(1); channel.basicConsume("trade.eq.q", false, consumer); int numMsgs = args.length > 0 ? new Integer(args[0]).intValue() : 1; for (int i=0; i<numMsgs; i++) { QueueingConsumer.Delivery msg = consumer.nextDelivery(); System.out.println("received: " + new String(msg.getBody())); Thread.sleep(1000); channel.basicAck(msg.getEnvelope().getDeliveryTag(), false); } AMQPCommon.close(channel); }
Example 6
Source File: Consumer.java From code with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost(Constant.ip); connectionFactory.setPort(Constant.port); connectionFactory.setVirtualHost("/"); Connection connection = connectionFactory.newConnection(); Channel channel = connection.createChannel(); String exchangeName = "test_qos_exchange"; String queueName = "test_qos_queue"; String routingKey = "qos.#"; channel.exchangeDeclare(exchangeName, "topic", true, false, null); channel.queueDeclare(queueName, true, false, false, null); channel.queueBind(queueName, exchangeName, routingKey); /* * prefetchSize:消息限制大小,一般为0,不做限制。 * prefetchCount:一次处理消息的个数,一般设置为1 * global:一般为false。true,在channel级别做限制;false,在consumer级别做限制 */ channel.basicQos(0, 1, false); // 限流方式 第一件事就是 autoAck设置为 false channel.basicConsume(queueName, false, new MyConsumer(channel)); }
Example 7
Source File: Worker.java From java-study with Apache License 2.0 | 5 votes |
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); //factory.setHost("localhost"); factory.setUri("amqp://guest:[email protected]:5672"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);//queue的持久化需要在声明时指定durable=True System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); //保证在接收端一个消息没有处理完时不会接收另一个消息 channel.basicQos(1); // channel.basicQos(0, 1, false); //这样RabbitMQ就会使得每个Consumer在同一个时间点最多处理一个Message。换句话说,在接收到该Consumer的ack前,他它不会将新的Message分发给它。 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); } }
Example 8
Source File: RpcTest.java From util4j with Apache License 2.0 | 5 votes |
public void rpcServer() throws Exception { //1、获取连接 Connection connection = RabbitMqConnectionFactoy.getConnection(); //2、声明信道 Channel channel = connection.createChannel(); //3、声明队列 channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null); channel.basicQos(1); DefaultConsumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope,BasicProperties properties, byte[] body) throws IOException { //获取并转成String String message = new String(body, "UTF-8"); String cid=properties.getCorrelationId(); System.out.println("server-->收到消息,msg :"+message+",cid:"+cid); String rsp=message+" rsp"; // 返回处理结果队列 channel.basicPublish("", properties.getReplyTo(), properties,rsp.getBytes("UTF-8")); // 确认消息,已经收到后面参数 multiple:是否批量.true:将一次性确认所有小于envelope.getDeliveryTag()的消息。 channel.basicAck(envelope.getDeliveryTag(), false); } }; channel.basicConsume(RPC_QUEUE_NAME, autoAck,consumer); Thread.sleep(1000000); //6、关闭通道 channel.close(); //7、关闭连接 connection.close(); }
Example 9
Source File: ProducerConsumer.java From util4j with Apache License 2.0 | 5 votes |
public void consumer1() throws Exception { //1、获取连接 Connection connection =RabbitMqConnectionFactoy.getConnection(); //2、声明通道 Channel channel = connection.createChannel(); //3、声明队列 channel.queueDeclare(QUEUE_NAME, false, false, false, null); //同一时刻服务器只会发送一条消息给消费者(如果设置为N,则当客户端堆积N条消息后服务端不会推送给客户端了) channel.basicQos(1);//每次处理1个 //4、定义队列的消费者 //定义消费者 DefaultConsumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope,BasicProperties properties, byte[] body) throws IOException { //获取并转成String String message = new String(body, "UTF-8"); System.out.println("-->消费者1号,收到消息,msg :"+message+",header:"+properties.getHeaders().toString()); /** * basicAck:成功消费,消息从队列中删除 basicNack:requeue=true,消息重新进入队列,false被删除 basicReject:等同于basicNack basicRecover:消息重入队列,requeue=true,发送给新的consumer,false发送给相同的consumer */ // channel.basicAck(envelope.getDeliveryTag(), false); // channel.basicReject(envelope.getDeliveryTag(), false);//拒绝此条消息,并重发到队列(可能再次受到此消息) // channel.basicRecover(true);//消息重发给其它消费者 channel.basicNack(envelope.getDeliveryTag(), false, false); } }; channel.basicConsume(QUEUE_NAME, autoAck,consumer); }
Example 10
Source File: Dispatcher.java From reactive with Creative Commons Zero v1.0 Universal | 5 votes |
public void dispatchMessages() throws Exception { Channel channel = AMQPCommon.connect(); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicQos(1); channel.basicConsume("trade.eq.q", false, consumer); java.util.Scanner input = new java.util.Scanner(System.in); System.out.print("Display Allocation Map? (y/n): "); display = input.next().equalsIgnoreCase("y"); input.close(); //start with 5 threads... for (long i=1;i<6;i++) { TradeProcessor processor = new TradeProcessor(this, i); threadpool.put(i, processor); processingCountMap.put(i, 0L); new Thread(()->processor.start()).start(); } displayAllocationMap(); while (true) { QueueingConsumer.Delivery msg = consumer.nextDelivery(); channel.basicAck(msg.getEnvelope().getDeliveryTag(), false); String trade = new String(msg.getBody()); String context = getContext(trade); Long threadId = 0L; if (allocationMap.containsKey(context)) { threadId = allocationMap.get(context); } else { threadId = getNextAvailableThread(); allocationMap.put(context, threadId); } processingCountMap.put(threadId, processingCountMap.get(threadId)+1); if (display) System.out.println("Dispatcher: Received " + trade); displayAllocationMap(); threadpool.get(threadId).addMessage(new String(msg.getBody())); } }
Example 11
Source File: AMQPContConsumer.java From reactive with Creative Commons Zero v1.0 Universal | 5 votes |
public static void main(String[] args) throws Exception { Channel channel = AMQPCommon.connect(); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicQos(1); channel.basicConsume("trade.eq.q", false, consumer); while (true) { QueueingConsumer.Delivery msg = consumer.nextDelivery(); System.out.println("received: " + new String(msg.getBody())); Thread.sleep(2000); channel.basicAck(msg.getEnvelope().getDeliveryTag(), false); } }
Example 12
Source File: Registration.java From NFVO with Apache License 2.0 | 5 votes |
/** * Sends a deregistration message to the NFVO * * @param brokerIp the rabbitmq broker ip * @param port the port of rabbitmq * @param username the username to connect with * @param password the password to connect with * @param virtualHost the virtualHost * @param managerCredentialUsername the username to remove * @param managerCredentialPassword the password to remove * @throws IOException In case of InterruptedException * @throws TimeoutException in case of TimeoutException */ public void deregisterPluginFromNfvo( String brokerIp, int port, String username, String password, String virtualHost, String managerCredentialUsername, String managerCredentialPassword) throws IOException, TimeoutException { String message = "{'username':'" + managerCredentialUsername + "','action':'deregister','password':'" + managerCredentialPassword + "'}"; ConnectionFactory factory = new ConnectionFactory(); factory.setHost(brokerIp); factory.setPort(port); factory.setUsername(username); factory.setPassword(password); factory.setVirtualHost(virtualHost); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); // check if exchange and queue exist channel.exchangeDeclarePassive("openbaton-exchange"); channel.queueDeclarePassive("nfvo.manager.handling"); channel.basicQos(1); AMQP.BasicProperties props = new AMQP.BasicProperties.Builder().contentType("text/plain").build(); channel.basicPublish("openbaton-exchange", "nfvo.manager.handling", props, message.getBytes()); channel.close(); connection.close(); }
Example 13
Source File: BatchWriterService.java From neo4j-mazerunner with Apache License 2.0 | 4 votes |
@Override protected void runOneIteration() throws Exception { logger.info("Connecting to RabbitMQ processor queue..."); 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); 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 = null; try { delivery = consumer.nextDelivery(40000L); if(delivery != null) { String message = new String(delivery.getBody()); System.out.println(" [x] Received processor message '" + message + "'"); // Deserialize the processor message Gson gson = new Gson(); ProcessorMessage processorMessage = gson.fromJson(message, ProcessorMessage.class); // Open the node property update list file from HDFS BufferedReader bufferedReader = FileUtil.readGraphAdjacencyList(processorMessage); switch (processorMessage.getMode()) { case Partitioned: PartitionedAnalysis.updatePartition(processorMessage, bufferedReader, graphDb); break; case Unpartitioned: if (Objects.equals(processorMessage.getAnalysis(), JobRequestType.COLLABORATIVE_FILTERING.toString().toLowerCase())) { Writer.asyncImportCollaborativeFiltering(bufferedReader, graphDb); } else { // Stream the the updates as parallel transactions to Neo4j Writer.asyncUpdate(processorMessage, bufferedReader, graphDb); } break; } // Close the stream bufferedReader.close(); System.out.println(" [x] Done"); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } catch (Exception ex) { ex.printStackTrace(); System.out.println("Waiting..."); // Hold on error cycle to prevent high throughput writes to console log Thread.sleep(5000); System.out.println("Recovered..."); if(delivery != null) channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } }
Example 14
Source File: Worker.java From neo4j-mazerunner with Apache License 2.0 | 4 votes |
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); 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); } }