Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP How do I implement queue processing in php

Tags:

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?

like image 580
ASHUTOSH Avatar asked Jul 06 '12 06:07

ASHUTOSH


People also ask

When to use Queues in PHP?

Queues are an important solution, especially when need to create a processing task that may take a long time to complete and the user or the creating process cannot wait until the task is finished. This is the case for instance of sending newsletter email messages to many users.

What is Queuing in PHP?

A Queue is a “first in, first out” or “FIFO” collection that only allows access to the value at the front of the queue and iterates in that order, destructively.


1 Answers

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.

like image 72
Maksim Kotlyar Avatar answered Dec 25 '22 05:12

Maksim Kotlyar