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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM