work模型
默认:平均分配,无论处理速度,平均分配到每个队列
消费者: 可以设置消费者通道,让通道每次只进来一个消息,
关闭消费者通道的自动确认,让消息消费完一个,在开始下一个。谁消费的快,谁先拿消息走
生产者:
public void test() throws IOException, TimeoutException {
// 连接对象被封装
// 获取连接对象
Connection connection = connectionFactory.newConnection();
// 获取连接通道
Channel channel = connection.createChannel();
// 通过通道,声明队列
channel.queueDeclare("hello",true,false,false,null);
//生产消息
for(int i = 0;i<10;i++){
channel.basicPublish("","hello",MessageProperties.PERSISTENT_TEXT_PLAIN,(i+ "内容").getBytes());
}
// 关闭通道
channel.close();
// 关闭连接
connection .close();
}
消费者1;
public void test() throws IOException, TimeoutException {
// 连接对象被封装
// 获取连接对象
Connection connection = connectionFactory.newConnection();
// 获取连接通道
Channel channel = connection.createChannel();
// 通过通道,声明队列
channel.queueDeclare("hello",true,false,false,null);
channe1.basicQos(1);
//消费消息
// 第二个参数,false 不会自己动确认消息
channel.basicConsume("hello",false,new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者1 : "+new String(body));
// 传输1 : 确认队列中哪个具体消息
// 参数2:是否开启多条消息同时确认
channel.basicAck(envelope.getDeliveryTag(),false);
}
});
}
消费者2;
public void test() throws IOException, TimeoutException {
// 连接对象被封装
// 获取连接对象
Connection connection = connectionFactory.newConnection();
// 获取连接通道
Channel channel = connection.createChannel();
// 通过通道,声明队列
channel.queueDeclare("hello",true,false,false,null);
channe1.basicQos(1);
//消费消息
// 第二个参数,false 不会自己动确认消息
channel.basicConsume("hello",fasle,new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者2 : "+ new String(body));
// 传输1 : 确认队列中哪个具体消息
// 参数2:是否开启多条消息同时确认
channel.basicAck(envelope.getDeliveryTag(),false);
}
});
}