zhuxue 2019-07-01
1.安装rabbit
require_once __DIR__.'/vendor/autoload.php'; use PhpAmqpLib\Connection\AMQPStreamConnection; use PhpAmqpLib\Exchange\AMQPExchangeType; use PhpAmqpLib\Message\AMQPMessage; $connection = new AMQPStreamConnection("127.0.0.1", 5672, "guest", "guest", "yedong_test"); //连接server $channel = $connection->channel(); //创建通道
$exchange="example_direct_exchange"; /* name: $exchange type: fanout 交换机类型 passive: false // don't check if an exchange with the same name exists durable: false // the exchange won't survive server restarts //是否是持久化 auto_delete: true //the exchange will be deleted once the channel is closed. */ $channel->exchange_declare($exchange, AMQPExchangeType::DIRECT, false, true, true);
3.创建队列
//参数 $queue = '', //队列名称 $passive = false, //检查是否村子啊 $durable = false, //是否持久化 $exclusive = false, //排外,①当前定义的队列是connection的channel是共享的,其他的connection是访问不到的。②当connection关闭的时候,队列将被删除。 $auto_delete = true, //空是自动删除 $nowait = false, // $arguments = array(), $ticket = null ![clipboard.png](/img/bVbrPP9) $channel->queue_declare("test_queue_3",true,true,false,false,false,[],null);
4.绑定队列和交换机,生成routing_key
$channel->queue_bind("example_direct_queue_2",$exchange,"routeTest1");
5.发送消息到队列
![clipboard.png](/img/bVbrPRr) $msg = new AMQPMessage($i, ['content_type' => 'text/plain','delivery_mode'=>2]); //2:持久化,重启不会丢失,默认为1,重启会丢失 $channel->basic_publish($msg, $exchange,"routeTest1");