php-amqplib rabbitmq发送消息并判断消息是否发送成功 ack comfirm机制

<?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();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值