Bootstrap

rabbitmq java 多线程_RabbitMQ入门_05_多线程消费同一队列

A. 多线程消费同一队列

消费一条消息往往比产生一条消息慢很多,为了防止消息积压,一般需要开启多个工作线程同时消费消息。在 RabbitMQ 中,我们可以创建多个 Consumer 消费同一队列。示意图如下:

c5e5014577a5a5691458fae3af839b04.png

gordon.study.rabbitmq.workqueue.Sender.java

public class Sender {

private static final String QUEUE_NAME = "tasks";

private String name;

public Sender(String name) {

this.name = name;

}

public void work() throws Exception {

ConnectionFactory factory = new ConnectionFactory();

factory.setHost("localhost");

Connection connection = factory.newConnection();

Channel channel = connection.createChannel();

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

for (int i = 0; i < 10;) {

String message = "NO. " + ++i;

TimeUnit.MILLISECONDS.sleep(100);

channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));

System.out.printf("(%1$s)[===>%2$s ] %3$s\n", name, ":" + QUEUE_NAME, message);

}

channel.close();

connection.close();

}

}

gordon.study.rabbitmq.workqueue.Receiver.java

public class Receiver {

priva

;