coinvestor/laravel-batchsqs

适用于 Laravel 的 Amazon SQS 队列驱动程序的替代方案。消息批量发送而不是逐条发送,如果您需要发送大量消息,这可能更高效。

v0.1.10 2021-08-26 08:05 UTC

README

为 Laravel 提供的 SQS 队列连接器,支持批量发送消息。

安装

要安装

composer require coinvestor/laravel-batchsqs

然后发布配置文件

artisan vendor:publish

(按提示选择 BatchSQSProvider 选项)

使用方法

此包提供了一个名为 batch-sqs 的队列连接器。在 connections 中创建一个块,就像通常一样

'connections' => [
        'batch-sqs' => [
            'driver'      => 'batch-sqs',
            'key'         => env('AWS_KEY', null),
            'secret'      => env('AWS_SECRET', null),
            'prefix'      => env('AWS_PREFIX', null),
            'queue'       => env('AWS_QUEUE', null),
            'region'      => env('AWS_REGION', null),
            'batch_size'  => 7,
        ],
// [...]

您可以使用所有常规的 Laravel SQS 队列配置选项。此外,您可以设置 batch_size 以定义每个批次包含多少条消息(一旦批次满载,消息将被释放到队列)。

当队列对象被销毁时(例如,在请求生命周期结束时,当 Laravel 关闭时),即使未达到批次大小限制,仍将发送等待发送到队列的消息。

发布前修改消息

当一批消息被释放到队列时,将触发 CoInvestor\BatchSQS\Queues\Events\BatchMessageReleasingEvent。要修改每个消息在到达队列之前,只需定义一个监听器,该监听器将检查消息,然后返回一个数组,该数组将在消息发布之前与消息合并。

<?php
use \CoInvestor\BatchSQS\Queues\Events\BatchMessageReleasingEvent;
class BatchMessageReleasingEventListener
{
    public function handle(BatchMessageReleasingEvent $event)
    {
        $return = [];

        // If the message is 'foo' it should be changed to 'foobar'
        if ($event->message['MessageBody'] == 'foo') {
            $return['MessageBody'] = 'foobar';
        }
        // If the queue name ends in .norbert, the message should have a message group id consisting of 128 '1's
        if (preg_match('/.*\.norbert/', $event->queue)) {
            $return['MessageGroupId'] = str_repeat("1", 128);
        }

        return $return;
    }
}

清空队列

您可能希望在队列满载之前发送批次到队列,或者完全丢弃它们。以下是方法:

use Illuminate\Support\Facades\Queue;

// Send all message batches to their respective queues
Queue::flush();

// Discard all message batches
Queue::flush(true);