php basic publish,【rabbitmq-Php】-发布Publish 与订阅Subscribe

742a685b42df871715138cff7068371c.png

发布/订阅,使用扇型交换机(fanout)

composer.json

### composer.json

{

"require": {

"php-amqplib/php-amqplib": ">=2.9.0"

}

}

发布端(Publish)

/**

* rabbitmq

* 发布/订阅

* Publish

* https://github.com/rabbitmq/rabbitmq-tutorials

* https://www.rabbitmq.com/tutorials/tutorial-three-php.html

*/

defined('DS') or define('DS', DIRECTORY_SEPARATOR);

require_once __DIR__. DS . 'vendor' .DS.'autoload.php';

use PhpAmqpLib\Connection\AMQPStreamConnection;

use PhpAmqpLib\Message\AMQPMessage;

$connection = new AMQPStreamConnection('192.168.0.83', 5672, 'admin', 'admin');

$channel = $connection->channel();

// 创建一个fanout类型的交换机,命名为logs

// 扇型交换机(fanout),它把消息发送给它所知道的所有队列

$channel->exchange_declare('logs', 'fanout', false, false, false);

$data = implode('...', array_slice($argv, 1));

if (empty($data)) {

$data = 'hello publish,subscribe!';

}

$msg = new AMQPMessage($data);

$channel->basic_publish($msg, 'logs');

$channel->close();

$connection->close();

订阅端(Subscribe)

/**

* rabbitmq

* 发布/订阅

* Subscribe

* https://github.com/rabbitmq/rabbitmq-tutorials

* https://www.rabbitmq.com/tutorials/tutorial-three-php.html

*/

defined('DS') or define('DS', DIRECTORY_SEPARATOR);

require_once __DIR__. DS . 'vendor' .DS.'autoload.php';

use PhpAmqpLib\Connection\AMQPStreamConnection;

$connection = new AMQPStreamConnection('192.168.0.83', 5672, 'admin', 'admin');

$channel = $connection->channel();

// 创建一个fanout类型的交换机,命名为logs

// 扇型交换机(fanout),它把消息发送给它所知道的所有队列

$channel->exchange_declare('logs', 'fanout', false, false, false);

// 定义临时队列

// 当与消费者(consumer)断开连接的时候,这个队列被立即删除

list($queue_name, ,) = $channel->queue_declare('', false, false, true, false);

// logs交换机将会把消息添加到我们的队列中

$channel->queue_bind($queue_name, 'logs');

// 订阅回调函数

$callback = function($msg){

echo 'Subscribe:', $msg->body, PHP_EOL;

};

$channel->basic_consume($queue_name, '', false, true, false, false, $callback);

while($channel->is_consuming()){

$channel->wait();

}

$channel->close();

$connection->close();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值