一、前言
核心需求如电商秒杀场景:若用户在下单后 10 分钟内未完成支付,系统需自动执行库存归还操作。
本方案采用 PHP 语言配合 Laravel 框架及 RabbitMQ 中间件,构建异步延迟消息队列机制。
二、场景
在电商业务中,用户下单后通常享有 20 至 30 分钟的付款窗口期。若超时未付,订单将进入异常处理流程并被取消,此过程可视为一种延迟队列的应用。
企业会议预定系统中,需在会议开始前半小时向所有预定用户发送通知提醒。
安全工单若超过 24 小时未被处理,系统将自动拉取企业微信群并提醒相关责任人。
外卖配送场景中,当距离超时时间仅剩 10 分钟时,系统需提醒外卖骑手即将超时。
…
上述多种业务场景均依赖于延迟队列功能以支持定时或延后触发的逻辑。
本文将重点探讨基于 RabbitMQ 的延迟队列实现方式。
具体实现上,推荐使用 RabbitMQ 的 rabbitmq_delayed_message_exchange 插件,该方案配置相对简单且易于集成。
三、安装RabbitMQ延迟队列插件
首先访问 RabbitMQ 官网获取插件下载链接。

建议直接下载最新版本,请根据当前使用的 RabbitMQ 版本号选择对应的插件版本进行下载。

将下载好的插件文件移动至 RabbitMQ 的 plugins 目录下。以 Mac 系统为例,路径通常为 /usr/local/lib/rabbitmq/mnesia/.../plugins(具体视安装方式而定)。

接着执行插件安装指令,命令如下。
rabbitmq-plugins enable rabbitmq_delayed_message_exchange

最后重启 RabbitMQ 服务,并刷新管理界面查看 exchanges 列表中是否出现该插件对应的交换机类型。

若能在交换机列表中看到 delayed exchange 类型,则表明延迟消息队列插件已成功安装。
四、在Laravel框架中进行使用
新建rabbitmq服务类,包含延迟消息队列生产消息,和消费消息,如下

具体代码实现如下。
<?php
namespace App\Http\Controllers\Service;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;
class RabbitmqServer
{
private $host = "127.0.0.1";
private $port = 5672;
private $user = "guest";
private $password = "guest";
private $msg;
private $channel;
private $connection;
// 过期时间
const TIMEOUT_5_S = 5; // 5s
const TIMEOUT_10_S = 10; // 10s
private $exchange_logs = "logs";
private $exchange_direct = "direct";
private $exchange_delayed = "delayed";
private $queue_delayed = "delayedQueue";
const EXCHANGETYPE_FANOUT = "fanout";
const EXCHANGETYPE_DIRECT = "direct";
const EXCHANGETYPE_DELAYED = "x-delayed-message";
public function __construct($type = false)
{
$this->connection = new AMQPStreamConnection($this->host, $this->port, $this->user, $this->password);
$this->channel = $this->connection->channel();
// 声明Exchange
$this->channel->exchange_declare($this->exchange_delayed, self::EXCHANGETYPE_DELAYED, false, true, false, false, false, new AMQPTable(["x-delayed-type" => self::EXCHANGETYPE_DIRECT]));
$this->channel->queue_declare($this->queue_delayed, false, true, false, false);
$this->channel->queue_bind($this->queue_delayed, $this->exchange_delayed, $this->queue_delayed);
}
/**
* delay creat message
*/
public function createMessageDelay($msg, $time)
{
$delayConfig = [
'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
'application_headers' => new AMQPTable(['x-delay' => $time * 1000])
];
$msg = new AMQPMessage($msg, $delayConfig);
return $msg;
}
/**
* delay send message
*/
public function sendDelay($msg, $time = self::TIMEOUT_10_S)
{
$msg = $this->createMessageDelay($msg, $time);;
$this->channel->basic_publish($msg, $this->exchange_delayed, $this->queue_delayed);
$this->channel->close();
$this->connection->close();
}
/**
* delay consum
*/
public function consumDelay()
{
$callback = function ($msg) {
echo ' [x] ', $msg->body, "\n";
$this->channel->basic_ack($msg->delivery_info['delivery_tag'], false);
};
$this->channel->basic_qos(null, 1, null);
$this->channel->basic_consume($this->queue_delayed, '', false, false, false, false, $callback);
echo ' [*] Waiting for logs. To exit press CTRL+C', "\n";
while (count($this->channel->callbacks)) {
$this->channel->wait();
}
$this->channel->close();
$this->connection->close();
}
}
随后新建 QueueController 控制器,用于测试向延迟消息队列中推送消息的功能。

控制器代码如下。
<?php
namespace App\Http\Controllers\Api\v1;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Service\RabbitmqServer;
use App\Jobs\Queue;
use Illuminate\Http\Request;
class QueueController extends Controller
{
//
public function index(Request $request)
{
//比如说现在是下订单操作
//需求:如果用户10分钟之内不支付订单就要取消订单,并且库存归还
$msg = $request->post();
$Rabbit = new RabbitmqServer("x-delayed-message");
//第一个参数发送的消息,第二个参数延迟多少秒
$Rabbit->sendDelay(json_encode($msg),5);
}
}
至此,可通过接口调试工具模拟调用接口,完成消息的生产与入队。
消息生产完成后需进行消费处理,此处利用 Laravel 的任务调度机制来触发消费逻辑,代码如下。

<?php
namespace App\Console\Commands;
use App\Http\Controllers\Service\RabbitmqServer;
use Illuminate\Console\Command;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
class RabbitmqConsumerCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'rabbitmq_consumer';//给消费者起个command名称
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
* @return int
*/
public function handle()
{
$Rabbit = new RabbitmqServer("x-delayed-message");
$Rabbit->consumDelay();
}
}
五、执行生产消息和消费消息
使用 Postman 模拟请求生产消息,运行效果如图所示。

接下来执行消费消息的命令。若设置延迟时间为 5 秒,则在等待相应时间后应能成功消费到消息。

通过以上步骤,即完成了基于 RabbitMQ 的 PHP 异步延迟消息队列的配置与验证。
关于 PHP 实现异步延迟消息队列的详细方法已介绍完毕。如需了解更多 PHP 异步延迟消息队列相关内容,欢迎查阅本站过往文章或继续浏览后续推荐内容,感谢大家的支持!