标签:port queue \n func env 发布者 rabbit sage declare
一、发布消息类(client.php),发布者
<?php $conn = [ ‘host‘ => ‘127.0.0.1‘, ‘port‘ => ‘5672‘, ‘login‘ => ‘guest‘, ‘password‘ => ‘guest‘, ‘vhost‘=>‘/‘ ]; //创建连接和channel $conn = new AMQPConnection($conn); if(!$conn->connect()) { die("Cannot connect to the broker!\n"); } $channel = new AMQPChannel($conn); // 用来绑定交换机和队列 $routingKey = ‘key_1‘; $ex = new AMQPExchange($channel); // 交换机名称 $exchangeName = ‘ex1‘; $ex->setName($exchangeName); // 设置交换机类型 $ex->setType(AMQP_EX_TYPE_DIRECT); // 设置交换机是否持久化消息 $ex->setFlags(AMQP_DURABLE); $ex->declare(); for($i=0; $i<5; ++$i){ echo "Send Message:".$ex->publish(date(‘H:i:s‘)."用户".$i."注册" , $routingKey )."\n"; }
二、接受消息类(server.php),订阅者
<?php $conn = [ ‘host‘ => ‘127.0.0.1‘, ‘port‘ => ‘5672‘, ‘login‘ => ‘guest‘, ‘password‘ => ‘guest‘, ‘vhost‘=>‘/‘ ]; //创建连接和channel $conn = new AMQPConnection($conn); if(!$conn->connect()) { die("Cannot connect to the broker!\n"); } $channel = new AMQPChannel($conn); $exchangeName = ‘ex1‘; //创建交换机 $ex = new AMQPExchange($channel); $ex->setName($exchangeName); $ex->setType(AMQP_EX_TYPE_DIRECT); //direct类型 $ex->setFlags(AMQP_DURABLE); //持久化 $ex->declare(); // 创建队列 $queueName = ‘queue1‘; $q = new AMQPQueue($channel); $q->setName($queueName); $q->setFlags(AMQP_DURABLE); $q->declareQueue(); // 用于绑定队列和交换机,跟 send.php 中的一致。 $routingKey = ‘key_1‘; $q->bind($exchangeName, $routingKey); //接收消息 $q->consume(function ($envelope, $queue) { $msg = $envelope->getBody(); echo $msg."\n"; //处理消息 }, AMQP_AUTOACK); $conn->disconnect();
三、需要将订阅者常驻于后台进程。
这里先使用下命令
php server.php
然后打开另一个终端,使用
php client.php
标签:port queue \n func env 发布者 rabbit sage declare
原文地址:https://www.cnblogs.com/licnlt/p/9498021.html