-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConsumer.php
More file actions
70 lines (55 loc) · 2.37 KB
/
Consumer.php
File metadata and controls
70 lines (55 loc) · 2.37 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
namespace ADT\BackgroundQueue\Broker\PhpAmqpLib;
use ADT\BackgroundQueue\BackgroundQueue;
use ADT\BackgroundQueue\Console\ReloadConsumersCommand;
use Exception;
use PhpAmqpLib\Exception\AMQPProtocolChannelException;
use PhpAmqpLib\Message\AMQPMessage;
class Consumer implements \ADT\BackgroundQueue\Broker\Consumer
{
private BackgroundQueue $backgroundQueue;
private Manager $manager;
public function __construct(Manager $manager, BackgroundQueue $backgroundQueue)
{
$this->manager = $manager;
$this->backgroundQueue = $backgroundQueue;
}
/**
* @throws Exception
*/
public function consume(string $queue, array $priorities, ?string $consumerLabel = null): void
{
// TODO Do budoucna cheme podporovat libovolné priority a ne pouze jejich výčet.
// Zde si musíme vytáhnout seznam existujících front. To lze přes HTTP API pomocí CURL.
$priorities = $this->manager->includeTopPriority($priorities, $consumerLabel);
// Sestavíme si seznam názvů front v RabbitMQ (tedy včetně priorit) a všechny inicializujeme
$queuesWithPriorities = [];
foreach ($priorities as $priority) {
$queueWithPriority = $this->manager->getQueueWithPriority($queue, $priority);
$queuesWithPriorities[] = $queueWithPriority;
$this->manager->createExchange($queueWithPriority);
$this->manager->createQueue($queueWithPriority, $queueWithPriority);
}
$this->manager->setupQos();
foreach ($queuesWithPriorities as $queue) {
$this->manager->getChannel()->basic_consume($queue, $queue, false, false, false, false, function(AMQPMessage $msg) use ($queuesWithPriorities) {
// Odpojím se od všech nabindovaných front
foreach ($queuesWithPriorities as $queuesWithPriority) {
$msg->getChannel()->basic_cancel($queuesWithPriority);
}
$msg->ack();
// Odpojím se od kanálu, abych uvolnil zprávy vyhrazené pro ostatní nabindované callbacky na ostatní fronty a zprávy mohly okamžitě zpracovat jiní konzumeři
$this->manager->closeChannel();
if ($msg->getBody() === Producer::DIE) {
die();
}
$queuesWithPriority = $msg->getConsumerTag();
list($queue, $priority) = $this->manager->parseQueueAndPriority($queuesWithPriority);
$this->backgroundQueue->process((int)$msg->getBody(), $queue, $priority);
});
}
while ($this->manager->getChannel()->is_consuming()) {
$this->manager->getChannel()->wait();
}
}
}