【rabbitmq-Php】-发布Publish 与订阅Subscribe

爷,独闯天下 提交于 2020-10-02 20:30:32


发布/订阅,使用扇型交换机(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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!