消息队列之公平分发
- 使用公平分发我们得设置:
channel.basicQos(1)
- 指该消费者在接收到队列里的消息但没有返回确认结果之前
- 队列不会将新的消息分发给该消费者。队列中没有被消费的消息不会被删除,还是存在于队列中
- 且要关闭自动答复
boolean autoACK = false
channel.basicConsume(QUEUE_NAME,autoACK,consumer);
basicQos和autoACK
是结合使用的,如果有两个设置了一次只获取一个另一个不设置,那么另一个将会有很多消息
1、发送者
public class Send {
private static final String QUEUE_NAME= "test_fair_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());
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
System.out.println("--send:"+msg);
}
}
channel.close();
connection.close();
}
}
接收者
public class WorkFairGet1 {
private static final String QUEUE_NAME= "test_fair_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);
channel.basicQos(1);
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);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
channel.basicAck(envelope.getDeliveryTag(),false);
}
}
};
boolean autoACK = false;
channel.basicConsume(QUEUE_NAME,autoACK,consumer);
}
}