RabbitMQ在php中的使用----发布与订阅

2021-01-18 11:12:48 浏览数 (1)

安装扩展

安装教程 rabbitmq和php的amqp扩展教程网上有很多,大家可以自行查询,例如:Linux系统安装RabbitMQ及PHP安装amqp拓展库详细教程

RabbitMQ文档推荐

不清楚里面的api的可以在文档中查询 RabbitMQ 中文文档

composer 依赖

创建 composer.json填写内容

代码语言:javascript复制
{
  "require": {
    "php-amqplib/php-amqplib": "^2.12"
  }
}
发布
代码语言:javascript复制
<?php
require_once __DIR__ . '/vendor/autoload.php';

use PhpAmqpLibConnectionAMQPStreamConnection;
use PhpAmqpLibMessageAMQPMessage;

$connect = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest', '/', false, 'AMQPLAIN', null, 'en_US', 5.0, 5.0);
$channel = $connect->channel();
$exchange = 'log';
$channel->exchange_declare($exchange, 'fanout', true, true, false);
//异步回调消息确认
$channel->set_ack_handler(
    function (AMQPMessage $message) {
        echo '消息确认内容' . $message->body . PHP_EOL;
    }
);
//异步回调,消息丢失处理
$channel->set_nack_handler(
    function (AMQPMessage $message) {
        echo '消息丢失' . $message->body . PHP_EOL;
    }
);
echo '生成扇形交换机' . $exchange . PHP_EOL;
for ($i = 0; $i < 100; $i  ) {
    $pushData = "嘻嘻---------$i";
    echo '发布消息' . $pushData . PHP_EOL;
    $msg = new AMQPMessage($pushData);
    $channel->basic_publish($msg, $exchange);
}
//等待消息确认
$channel->wait_for_pending_acks();
$channel->close();
$connect->close();
订阅
代码语言:javascript复制
<?php
require_once __DIR__ . '/vendor/autoload.php';

use PhpAmqpLibConnectionAMQPStreamConnection;

$connect = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest', '/', false, 'AMQPLAIN', null, 'en_US', 5.0, 5.0);
$channel = $connect->channel();
$exchange = 'log';
$channel->exchange_declare($exchange, 'fanout', true);
//定义临时queue
list($queue) = $channel->queue_declare('', false, false, true, false);
//绑定
$channel->queue_bind($queue, $exchange);
//回调
$callback = function ($msg) {
    echo '订阅消息:' . $msg->body . PHP_EOL;
};
$channel->basic_consume($queue, '', false, false, false, false, $callback);
while ($channel->is_consuming()) {
    $channel->wait();
}
$channel->close();
$connect->close();
呈现效果

打赏赞(1)微海报分享

0 人点赞