沃梦达 / 编程问答 / php问题 / 正文

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

PHP How do I implement queue processing in php(PHP 如何在 php 中实现队列处理)

本文介绍了PHP 如何在 php 中实现队列处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将我的客户(通过邮寄)发送的数据放在一个队列中,我的服务器上的一个 php 脚本首先检查队列是否为空.如果队列不为空,那么脚本会一一处理队列中的所有数据.我该怎么做?

I want the data sent by my clients (via post) to be placed in a queue and a php script on my server first checks if the queue is empty. If the queue is not empty, then the script shall process all the data in the queue one by one.How do I do this?

推荐答案

使用 入队 库.首先,您可以从多种transsports中进行选择,如 AMQP、STOMP、Redis、Amazon SQS、Filesystem 等.

This is something you could easily do with enqueue library. First, you can choose from a variety of transports, such as AMQP, STOMP, Redis, Amazon SQS, Filesystem and so on.

其次,它超级好用.让我们从安装开始:

Secondly, That's super easy to use. Let's start from installation:

您必须安装 enqueue/simple-client 库和 一种传输方式.假设您选择文件系统之一,请安装 enqueue/fs 库.总结一下:

You have to install the enqueue/simple-client library and one of the transports. Assuming you choose the filesystem one, install enqueue/fs library. To summarize:

composer require enqueue/simple-client enqueue/fs 

现在让我们看看如何从 POST 脚本发送消息:

Now let's see how you can send messages from your POST script:

<?php
// producer.php

use EnqueueSimpleClientSimpleClient;

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 EnqueueSimpleClientSimpleClient;
use EnqueuePsrPsrProcessor;
use EnqueuePsrPsrMessage;

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 进程,在本地计算机上,您无需任何额外的库或包即可运行它.

Run as many consumer.php processes as you by using supervisord or other process managers, on local computer you can run it without any extra libs or packages.

这是一个基本示例,并且 enqueue 有许多其他功能可能会派上用场.如果您有兴趣,请查看 入队文档出去.

That's a basic example and enqueue has a lot of other features that might come in handy. If you are interested, check the enqueue documentation out.

这篇关于PHP 如何在 php 中实现队列处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:PHP 如何在 php 中实现队列处理

基础教程推荐