我不熟悉使用队列进行密集处理。我有一个应用程序,它将上传一个短视频,用 FFMPEG 处理它,然后使用他们的 API 上传到 youtube,然后与我的数据库交互。我的问题:
我应该使用两个不同的队列吗?一个要处理,然后将其交给另一个队列进行上传?或者我应该把所有的处理都放在一个 worker 身上?
可以与工作人员的数据库交互还是应该以其他方式进行?
最佳答案
我建议使用两个不同的队列,一个用于图像处理,一个用于将其上传到 youtube。从队列工作人员查询数据库是完全可以的,尽管您可以在消息中传递所有必需的数据,因此您不需要 db。
以下是如何使用 enqueue 实现类似的功能图书馆。
您必须安装 enqueue/simple-client
图书馆和 one of the transports .假设您选择了文件系统之一,那么让我们安装它:
composer require enqueue/simple-client enqueue/fs
现在让我们看看如何从 POST 脚本发送消息:
<?php
// producer.php
use Enqueue\SimpleClient\SimpleClient;
include __DIR__.'/vendor/autoload.php';
$client = new SimpleClient('file://'); // the queue will store messages in tmp folder
// you uploaded the file to your server,
// and now you have a path to the file.
// I assume it is in the $movieFile var.
$client->sendCommand('process_movie', $movieFile);
消费脚本:
<?php
// consumer.php
use Enqueue\Client\Config;
use Enqueue\SimpleClient\SimpleClient;
use Enqueue\Psr\PsrProcessor;
use Enqueue\Psr\PsrMessage;
include __DIR__.'/vendor/autoload.php';
$client = new SimpleClient('file://');
$client->bind(Config::COMMAND_TOPIC, 'process_movie', function(PsrMessage $psrMessage) use ($client) {
$movieFile = $psrMessage->getBody();
// a movie processing logic here
// once we have done with processing we can send a message to upload_movie queue.
$client->sendCommand('upload_movie', $movieFile);
return PsrProcessor::ACK;
});
$client->bind(Config::COMMAND_TOPIC, 'upload_movie', function(PsrMessage $psrMessage) {
$movieFile = $psrMessage->getBody();
// a movie uploading logic here
return PsrProcessor::ACK;
});
// this call is optional but it worth to mention it.
// it configures a broker, for example it can create queues and excanges on RabbitMQ side.
$client->setupBroker();
$client->consume();
尽可能多地运行
consumer.php
使用 supervisord 像您一样处理或其他进程管理器,您可以在本地计算机上运行它而无需任何额外的库或包。这是一个基本示例,并且 enqueue 有许多其他功能可能会派上用场。如果您有兴趣,请查看enqueue documentation出去。
关于PHP队列实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28814584/