-
Notifications
You must be signed in to change notification settings - Fork 2
/
consumer.php
48 lines (36 loc) · 1.07 KB
/
consumer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?php
require 'vendor/autoload.php';
// RabbitMQ init.
$queue = new RabbitMQ('localhost');
$queue
->exchangeDeclare('exchange_name')
->queueDeclare('queue_name')
->bindQueueToExchange('routing_key');
// consumer limit.
$maxConsumerCount = 3;
$currentConsumerCount = $queue->consumerCount();
if ($currentConsumerCount >= $maxConsumerCount) {
exit("There are enough consumers. Exit\n");
}
// consumer ttl.
$start = time();
$ttl = 1800; // second
echo "[*] Waiting for tasks..\n";
// consume callback.
$queue->consume(function ($msg) use ($start, $ttl)
{
// do task.
echo $msg->body;
// OR do it in the background.
$message = base64_encode(serialize($msg->body)); // serialize and encode to send as cli argument.
$workerFile = realpath(__DIR__) . '/worker.php';
exec("nohup /usr/bin/php {$workerFile} {$message} > /dev/null 2>&1&");
// stop consuming when ttl is reached.
if (($start + $ttl) < time()) {
exit("Need restart. Exit\n");
}
});
// wait for task
$queue->wait();
// close connections
$queue->closeConnection();