欢迎大家关注我公众号“从零开始的it转行生”

rabbitmq的拉模式

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

posted @ 2020-11-08 13:02  大佬健  阅读(649)  评论(2编辑  收藏  举报

欢迎大家关注我公众号“从零开始的it转行生”