PHP How do I implement queue processing in php
php, queue
Solution
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:
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
Now let's see how you can send messages from your POST script:
<?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');
The consumption script:
<?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();
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.
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.
Problem
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?