rabbitmq的拉模式
在rabbitmq(一)-基本入門我們已經展示了rabbitmq的推模式(mq主動推送,消費者監聽)
其實rabbitmq還提供了一種拉模式;
1、直接上示例代碼:
rabbitmq(一)-基本入門的基礎上
我們把DemoLister注釋掉

同時增加主動獲取消息的接口
@GetMapping("getMq")
public String getMq() throws IOException {
ConnectionFactory connectionFactory = rabbitTemplate.getConnectionFactory();
Connection connection = connectionFactory.createConnection();
Channel channel = connection.createChannel(false);
String queueName = "demo";
boolean autoAck = false ;
channel.basicQos(1);
GetResponse response= channel.basicGet(queueName, autoAck);
if(null == response){
return "沒有消息";
}
byte[] body = response.getBody();
String msg = new String(body);
channel.basicAck(response.getEnvelope().getDeliveryTag(),false);
return msg;
}
2、模擬過程
執行命令curl localhost:8080/sendMq?msg=ssg發送消息

執行命令curl localhost:8080/getMq獲取消息

再執行一次命令curl localhost:8080/getMq獲取消息

備注
不能將拉模式放在一個循環里來代替推模式;
這樣做會嚴重影響 RabbitMQ的性能。
如果要實現高吞吐量,消費者理應使用推模式。
代碼地址:
git clone -b teacher-pushpoll https://gitee.com/guoeryyj/rabbitmq-teacher.git
