PHP队列实现


PHP queue implementation

我对将队列用于密集型进程很陌生。我有一个应用程序,将上传一个短视频,用FFMPEG处理,然后使用他们的API上传到youtube,然后与我的数据库交互。我的问题:

我应该使用两个不同的队列吗?一个要处理,然后交给另一个队列上传?或者我应该把所有的处理都放在一个工人身上?

与工作人员的数据库交互可以吗?还是应该用其他方式?

我建议使用两个不同的队列,一个用于图像处理,另一个用于上传到youtube。从队列工作者那里查询数据库是完全可以的,不过您可以在消息中传递所有必需的数据,这样就不需要数据库了。

以下是如何使用入队库实现类似的功能。

您必须安装enqueue/simple-client库和其中一个传输。假设您选择了文件系统,那么让我们安装它:

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();

通过使用supervisord或其他进程管理器运行尽可能多的consumer.php进程,在本地计算机上,您可以在没有任何额外的库或包的情况下运行它。

这是一个基本的例子,enqueue还有很多其他功能可能会派上用场。如果您感兴趣,请查看排队文档。