1、安装rabbitmq
怎么安装rabbitmq请查看之前课程,如果已经安装,请略过此步。
2、创建vendor文件夹或是直接采用PHP框架
mkdir vendor
3、进入文件
cd vendor
4、安装php扩展
composer require php-amqplib/php-amqplib
5、进入上级创建delay文件夹
cd ../
mkdir delay
6、进入delay文件并创建生产者php
cd delay
touch delay_pub.php
7、输入delay生产者内容
<?php
require_once '../vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;
$v_host = 'order';
$exc_name ='delay_exc_pay';
$routing_key = 'delay_route_pay';
$queue_name = 'delay_queue_pay';
$ttl = 20000;
$connection = new AMQPStreamConnection('localhost',5672,'wangyulong','wangyulong',$v_host);
$channel = $connection->channel();
$channel->exchange_declare($exc_name,'x-delayed-message',false,true,false);
$args = new AMQPTable(['x-delayed-type'=>'direct']);
$channel->queue_declare($queue_name,false,true,false,false,false,$args);
$channel->queue_bind($queue_name,$exc_name,$routing_key);
$data = 'this is dead message';
$arr = ['delivery_mode'=>AMQPMEssage::DELIVERY_MODE_PERSISTENT,'application_headers'=>new AMQPTable(['x-delay'=>$ttl])];
$msg = new AMQPMessage($data,$arr);
$channel->basic_publish($msg,$exc_name,$routing_key);
$channel->close();
$connection->close();
8、创建消费者php
touch delay_worker.php
9、输入delay消费者内容
<?php
require_once '../vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
$v_host ='order';
$exc_name ='delay_exc_pay';
$routing_key = 'delay_route_pay';
$queue_name = 'delay_queue_pay';
$connection = new AMQPStreamConnection('localhost',5672,'wangyulong','wangyulong',$v_host);
$channel = $connection->channel();
$channel->exchange_declare($exc_name,'x-delayed-message',false,true,false);
$channel->queue_bind($queue_name,$exc_name,$routing_key);
$callback = function($msg){
echo 'received ' ,$msg->body,"\n";
$msg->ack();
};
$channel->basic_qos(null,1,null);
$channel->basic_consume($queue_name,'',false,false,false,false,$callback);
while($channel->is_open()){
$channel->wait();
}
$channel->close();
$connection->close();
10、执行消费者
php delay_worker.php
11、执行生产者
php delay_pub.php