1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Jellyfish\QueueRabbitMq; |
6
|
|
|
|
7
|
|
|
use Jellyfish\Queue\DestinationInterface; |
8
|
|
|
use Jellyfish\Queue\MessageInterface; |
9
|
|
|
|
10
|
|
|
class FanoutConsumer extends AbstractConsumer |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @param \Jellyfish\Queue\DestinationInterface $destination |
14
|
|
|
* |
15
|
|
|
* @return \Jellyfish\Queue\MessageInterface|null |
16
|
|
|
*/ |
17
|
|
|
public function receiveMessage(DestinationInterface $destination): ?MessageInterface |
18
|
|
|
{ |
19
|
|
|
$this->createQueueAndBind($destination); |
20
|
|
|
|
21
|
|
|
return $this->doReceiveMessage($destination); |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @param \Jellyfish\Queue\DestinationInterface $destination |
26
|
|
|
* @param int $limit |
27
|
|
|
* |
28
|
|
|
* @return \Jellyfish\Queue\MessageInterface[] |
29
|
|
|
*/ |
30
|
|
|
public function receiveMessages(DestinationInterface $destination, int $limit): array |
31
|
|
|
{ |
32
|
|
|
$receivedMessages = []; |
33
|
|
|
$this->createQueueAndBind($destination); |
34
|
|
|
|
35
|
|
|
for ($i = 0; $i < $limit; $i++) { |
36
|
|
|
$receivedMessage = $this->doReceiveMessage($destination); |
37
|
|
|
|
38
|
|
|
if ($receivedMessage === null) { |
39
|
|
|
return $receivedMessages; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
$receivedMessages[] = $receivedMessage; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
return $receivedMessages; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @param \Jellyfish\Queue\DestinationInterface $destination |
50
|
|
|
* |
51
|
|
|
* @return void |
52
|
|
|
*/ |
53
|
|
|
protected function createQueueAndBind(DestinationInterface $destination): void |
54
|
|
|
{ |
55
|
|
|
try { |
56
|
|
|
$backupConnection = clone $this->connection; |
57
|
|
|
$this->connection->createQueueAndBind($destination); |
58
|
|
|
$backupConnection->getChannel()->close(); |
59
|
|
|
} catch (\Exception $exception) { |
60
|
|
|
if ($exception->getCode() === 404) { |
61
|
|
|
$this->connection = $backupConnection; |
62
|
|
|
$exchange = clone $destination; |
63
|
|
|
$exchange->setName($destination->getProperty('bind')); |
|
|
|
|
64
|
|
|
$this->connection->createExchange($exchange); |
65
|
|
|
$this->connection->createQueueAndBind($destination); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|