安装扩展
安装教程 rabbitmq
和php的amqp
扩展教程网上有很多,大家可以自行查询,例如:Linux系统安装RabbitMQ及PHP安装amqp拓展库详细教程
RabbitMQ文档推荐
不清楚里面的api的可以在文档中查询 RabbitMQ 中文文档
composer 依赖
创建 composer.json
填写内容
{
"require": {
"php-amqplib/php-amqplib": "^2.12"
}
}
生产者
代码语言:javascript复制<?php
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLibConnectionAMQPStreamConnection;
use PhpAmqpLibMessageAMQPMessage;
//连接mq
$connect = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest', '/', false, 'AMQPLAIN', null, 'en_US', 5.0, 5.0);
//建立通道
$channel = $connect->channel();
$queueName = 'hello';
//确认投放队列,并将队列持久化
$channel->queue_declare($queueName, false, true, false, 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;
}
);
//开启消息确认
$channel->confirm_select();
for ($i = 0; $i < 100; $i ) {
$pushData = "hello world---------$i";
$msg = new AMQPMessage($pushData);
$channel->basic_publish($msg, '', $queueName);
echo $pushData . PHP_EOL;
}
//阻塞等待消息确认 监听成功或失败返回结束
$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();
$queueName = 'hello';
$channel->queue_declare($queueName);
echo '创建队列成功' . PHP_EOL;
$callback = function ($msg) {
echo '接收到消息' . $msg->body . PHP_EOL;
};
$channel->basic_consume($queueName, '', false, false, false, false, $callback);
while ($channel->is_consuming()) {
$channel->wait();
}
$channel->close();
$connect->close();
呈现效果
打赏赞微海报分享