Provicer
package WorkQuene;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import utils.RabbitMQUtil;
import java.io.IOException;
/**
* @ProjectName: MyRabbitMQ
* @Package: WorkQuene
* @ClassName: Provider
* @Author: zxh
* @Description:
* @Date: 2022/1/12 17:31
* @Version: 1.0
*/
public class Provider {
public static void main(String[] args) throws IOException {
//获取连接对象
Connection connection = RabbitMQUtil.getConnection();
//获取通道对象
Channel channel = connection.createChannel();
//通过通道声明队列
channel.queueDeclare("work", true, false, false, null);
//生产消息
for (int i = 0; i < 100; i++) {
channel.basicPublish("", "work", null, (i + "work queue").getBytes());
}
//关闭
RabbitMQUtil.closeAll(channel, connection);
}
}
consumer1(处理的慢)
package WorkQuene;
import com.rabbitmq.client.*;
import utils.RabbitMQUtil;
import java.io.IOException;
/**
* @ProjectName: MyRabbitMQ
* @Package: WorkQuene
* @ClassName: Customer1
* @Author: zxh
* @Description:
* @Date: 2022/1/12 17:59
* @Version: 1.0
*/
public class Customer1 {
public static void main(String[] args) throws IOException {
//获取连接对象
Connection connection = RabbitMQUtil.getConnection();
//获取通道对象
final Channel channel = connection.createChannel();
//每次只能消费一个消息,避免一下消费了多个消息,但是在处理的过程中宕机导致未被处理的消息丢失
channel.basicQos(1);
//通过通道声明队列
channel.queueDeclare("work", true, false, false, null);
//参数1:队列名称
//队列2:消息自动确认 消费者自动向RabbitMQ确认消息消费 false 不会自动确认消息,即使消息被消费了,未被处理也不会显示被消费
channel.basicConsume("work",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));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
channel.basicAck(envelope.getDeliveryTag(),false);
}
});
}
}
消费者2(处理的快)
package WorkQuene;
import com.rabbitmq.client.*;
import utils.RabbitMQUtil;
import java.io.IOException;
/**
* @ProjectName: MyRabbitMQ
* @Package: WorkQuene
* @ClassName: Customer1
* @Author: zxh
* @Description:
* @Date: 2022/1/12 17:59
* @Version: 1.0
*/
public class Customer2 {
public static void main(String[] args) throws IOException {
//获取连接对象
Connection connection = RabbitMQUtil.getConnection();
//获取通道对象
final Channel channel = connection.createChannel();
//每次只能消费一个消息,避免一下消费了多个消息,但是在处理的过程中宕机导致未被处理的消息丢失
channel.basicQos(1);
//通过通道声明队列
channel.queueDeclare("work", true, false, false, null);
channel.basicConsume("work",false,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:是否开启多个消息同时确认 false:一次确认一个消息
channel.basicAck(envelope.getDeliveryTag(),false);
}
});
}
}