PHP如何在php中实现队列处理

标签 php queue

我希望将我的客户(通过邮寄)发送的数据放在一个队列中,我的服务器上的一个 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/

相关文章:

php - 如何处理购物车表中的更新查询

java - 如何用jboss创建临时jms队列?

环形缓冲区实现队列的代码

python - 使用两个堆栈 Python 实现一个队列

php - 如何在不连接数据库的情况下创建 MySQL 准备语句字符串

javascript - javascript 中的 html 不工作

使用 plusapi 在 google moment 中发帖时 PHP 授权失败

php - 如何在php中比较日期与数据库中存储的日期

python - 如何最有效地使用 collections.deque(popleft 与 appendleft)

java - 对 Java 的垃圾收集器如何工作的困惑(节点 + 队列)