我希望将我的客户(通过邮寄)发送的数据放在一个队列中,我的服务器上的一个 php 脚本首先检查队列是否为空。如果队列不为空,那么脚本会一一处理队列中的所有数据。我该怎么做?
最佳答案
这是您可以使用 enqueue 轻松完成的事情图书馆。首先,您可以从多种选择中选择 transports ,例如 AMQP、STOMP、Redis、Amazon SQS、Filesystem 等。
其次,它非常易于使用。让我们从安装开始:
您必须安装enqueue/simple-client
库和one of the transports .假设您选择文件系统,安装 enqueue/fs
库。总结:
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
$client->sendEvent('a_topic', 'aMessageData');
消费脚本:
<?php
// consumer.php
use Enqueue\SimpleClient\SimpleClient;
use Enqueue\Psr\PsrProcessor;
use Enqueue\Psr\PsrMessage;
include __DIR__.'/vendor/autoload.php';
$client = new SimpleClient('file://');
$client->bind('a_topic', 'a_processor_name', function(PsrMessage $psrMessage) {
// processing 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 documentation出去。
关于PHP如何在php中实现队列处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11357187/