<?php
require_once '../vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
$exchangeName = 'test_exchange';
$queueName = 'test_queue';
$routeKey = 'test_routekey';
$connection = new AMQPStreamConnection('127.0.0.1', 5672, 'test', 'test123', '/');
$channel = $connection->channel();
//推送成功
$channel->set_ack_handler(
function (AMQPMessage $message) {
echo "发送成功: " . $message->body . PHP_EOL;
}
);
//推送失败
$channel->set_nack_handler(
function (AMQPMessage $message) {
echo "发送失败: " . $message->body . PHP_EOL;
}
);
/*
* bring the channel into publish confirm mode.
* if you would call $ch->tx_select() before or after you brought the channel into this mode
* the next call to $ch->wait() would result in an exception as the publish confirm mode and transactions
* are mutually exclusive
*/
/*
* 进入发布确认模式。
* 如果在将通道引入此模式之前或之后调用$ch->tx_select()
* 下一个调用$ch->wait()将导致发布确认模式和事务异常
* 是互斥的
*/
$channel->confirm_select(); // 发布确认模式
// 通道
$channel->exchange_declare($exchangeName, 'direct', false, false, false);
// 队列
$channel->queue_declare($queueName, false, false, false, false);
// 使用routeKey绑定交换机和队列
$channel->queue_bind($queueName, $exchangeName, $routeKey);
//$channel->wait_for_pending_acks();
for ($i = 0; $i < 10; $i++) {
$msg = new AMQPMessage('Hello World!'.$i);
$channel->basic_publish($msg, $exchangeName, $routeKey);
}
/*
* you do not have to wait for pending acks after each message sent. in fact it will be much more efficient
* to wait for as many messages to be acked as possible.
*/
/*
*您不必在每条消息发送后等待挂起的acks。事实上,这样会更有效率
*等待尽可能多的邮件被屏蔽。
*/
$channel->wait_for_pending_acks();
// 监听成功或失败返回结束 成功/失败 => set_ack_handler/set_nack_handler
$channel->close();
$connection->close();