当前位置:   article > 正文

RabbitMQ-消息队列延迟队列二

RabbitMQ-消息队列延迟队列二

1、安装rabbitmq

怎么安装rabbitmq请查看之前课程,如果已经安装,请略过此步。

2、创建vendor文件夹或是直接采用PHP框架

mkdir vendor

3、进入文件

cd vendor

4、安装php扩展

composer require php-amqplib/php-amqplib

5、进入上级创建delay文件夹

  1. cd ../
  2. mkdir delay

6、进入delay文件并创建生产者php

  1. cd delay
  2. touch delay_pub.php

7、输入delay生产者内容

  1. <?php
  2. require_once '../vendor/autoload.php';
  3. use PhpAmqpLib\Connection\AMQPStreamConnection;
  4. use PhpAmqpLib\Message\AMQPMessage;
  5. use PhpAmqpLib\Wire\AMQPTable;
  6. $v_host = 'order';
  7. $exc_name ='delay_exc_pay';
  8. $routing_key = 'delay_route_pay';
  9. $queue_name = 'delay_queue_pay';
  10. $ttl = 20000;
  11. $connection = new AMQPStreamConnection('localhost',5672,'wangyulong','wangyulong',$v_host);
  12. $channel = $connection->channel();
  13. $channel->exchange_declare($exc_name,'x-delayed-message',false,true,false);
  14. $args = new AMQPTable(['x-delayed-type'=>'direct']);
  15. $channel->queue_declare($queue_name,false,true,false,false,false,$args);
  16. $channel->queue_bind($queue_name,$exc_name,$routing_key);
  17. $data = 'this is dead message';
  18. $arr = ['delivery_mode'=>AMQPMEssage::DELIVERY_MODE_PERSISTENT,'application_headers'=>new AMQPTable(['x-delay'=>$ttl])];
  19. $msg = new AMQPMessage($data,$arr);
  20. $channel->basic_publish($msg,$exc_name,$routing_key);
  21. $channel->close();
  22. $connection->close();

8、创建消费者php

touch delay_worker.php

9、输入delay消费者内容

  1. <?php
  2. require_once '../vendor/autoload.php';
  3. use PhpAmqpLib\Connection\AMQPStreamConnection;
  4. $v_host ='order';
  5. $exc_name ='delay_exc_pay';
  6. $routing_key = 'delay_route_pay';
  7. $queue_name = 'delay_queue_pay';
  8. $connection = new AMQPStreamConnection('localhost',5672,'wangyulong','wangyulong',$v_host);
  9. $channel = $connection->channel();
  10. $channel->exchange_declare($exc_name,'x-delayed-message',false,true,false);
  11. $channel->queue_bind($queue_name,$exc_name,$routing_key);
  12. $callback = function($msg){
  13. echo 'received ' ,$msg->body,"\n";
  14. $msg->ack();
  15. };
  16. $channel->basic_qos(null,1,null);
  17. $channel->basic_consume($queue_name,'',false,false,false,false,$callback);
  18. while($channel->is_open()){
  19. $channel->wait();
  20. }
  21. $channel->close();
  22. $connection->close();

10、执行消费者

php delay_worker.php

11、执行生产者

php delay_pub.php
此时你会发现只有delay消费者并没有数据,而是退后2秒才有数据。这就是rabbitmq delay延迟队列工作模式硬实力
延迟队列需要提前添加交换机
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/黑客灵魂/article/detail/1018979
推荐阅读
相关标签
  

闽ICP备14008679号