rabbitmq的ack confirm机制

1.下载amqplib类包 新建一个composer.json的文件,内容如下所示

{
    "require": {
        "php-amqplib/php-amqplib": ">=2.6.1"
    }
}

然后执行 composer install 

下载成功后vendor文件夹里有php-amqplib库,且有一个autoload.php文件可以使用自动加载

<?php

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Exchange\AMQPExchangeType;
use PhpAmqpLib\Message\AMQPMessage;

include(__DIR__ . '/config.php');

$exchange = 'someExchange';
$queueName = "queue_2";
$routeKey = "key_2";
$connection = new AMQPStreamConnection(HOST, PORT, USER, PASS, VHOST);
$channel = $connection->channel();

//推送成功
$channel->set_ack_handler(
    function (AMQPMessage $message) {
        //update 订单表 set is_send_succ=ture
        echo "Message acked with content " . $message->body . PHP_EOL;

    }
);

//推送失败
$channel->set_nack_handler(
    function (AMQPMessage $message) {
        //update 订单表 set is_send_succ=false
        echo "Message nacked with content " . $message->body . PHP_EOL;
    }
);

$channel->confirm_select();

/*
    name: $exchange
    type: fanout
    passive: false // don't check if an exchange with the same name exists
    durable: false // the exchange won't survive server restarts
    auto_delete: true //the exchange will be deleted once the channel is closed.
*/

$channel->exchange_declare($exchange, AMQPExchangeType::FANOUT, false, false, true);
// 队列
$channel->queue_declare($queueName, false, false, false, false);

// 使用routeKey绑定交换机和队列
$channel->queue_bind($queueName, $exchange, $routeKey);

/*
 * watching the amqp debug output you can see that the server will ack the message with delivery tag 1 and the
 * multiple flag probably set to false
 */

$channel->wait_for_pending_acks();
$i = 1;
while ($i <= 10) {
    $msg = new AMQPMessage($i++, array('content_type' => 'text/plain'));
    $channel->basic_publish($msg, $exchange);
}

/*
 * 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.
 */

$channel->wait_for_pending_acks();

$channel->close();
$connection->close();

保证消息100%发送成功思路

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值