消息队列之轮询分发
1、什么是轮询
一个生产者对应多个消费者,生产者发送多次消息,是采用轮询的机制,公平的分给每一个消费者。
2、轮询代码
//发送消息
public class Send {
private static final String QUEUE_NAME= "test_work_queue";
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = ConnectionUtils.getConnection();
Channel channel = connection.createChannel();
//声明队列
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
for (int i=0;i<50;i++){
String msg="hello" + i;
channel.basicPublish("",QUEUE_NAME,null,msg.getBytes());
System.out.println("--send:"+msg);
}
channel.close();
connection.close();
}
}
//接受者1
public class MQGet {
private static final String QUEUE_NAME= "test_work_queue";
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = ConnectionUtils.getConnection();
Channel channel = connection.createChannel();
//声明队列
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
Consumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
super.handleDelivery(consumerTag, envelope, properties, body);
String msg = new String(body,"utf-8");
System.out.println("接收消息:"+msg);
}
};
channel.basicConsume(QUEUE_NAME,true,consumer);
}
}
//接收者2
public class MQGet2 {
private static final String QUEUE_NAME= "test_work_queue";
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = ConnectionUtils.getConnection();
Channel channel = connection.createChannel();
//声明队列
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
Consumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
super.handleDelivery(consumerTag, envelope, properties, body);
String msg = new String(body,"utf-8");
System.out.println("接收消息:"+msg);
}
};
channel.basicConsume(QUEUE_NAME,true,consumer);
}
}
//接收者3
public class MQGet3 {
private static final String QUEUE_NAME= "test_work_queue";
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = ConnectionUtils.getConnection();
Channel channel = connection.createChannel();
//声明队列
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
Consumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
super.handleDelivery(consumerTag, envelope, properties, body);
String msg = new String(body,"utf-8");
System.out.println("接收消息:"+msg);
}
};
channel.basicConsume(QUEUE_NAME,true,consumer);
}
}
每当发送一个消息给服务器,服务器都会按照顺序轮流分发给3个消费者