rabbitmq二---均勻分配訊息給每個接收者,prefetchCount設定均勻分配的個數
阿新 • • 發佈:2018-12-29
傳送端的程式如下:
channel.basicPublish("", TASK_QUEUE_NAME,MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
//傳送(使用預設交換機,routing-key,其他屬性的訊息——路由標題等(這裡持久化),訊息體)
System.out.println(" [x] Sent '" + message + "'");
channel.close();
connection.close()
接收端的程式如下:
channel.basicQos(1);//告訴RabbitMQ同一時間給一個訊息給消費者 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);//下一個訊息 } private static void doWork(String task) throws InterruptedException { for (char ch : task.toCharArray()) { if (ch == '.') Thread.sleep(1000);//這裡是假裝我們很忙 } } }