-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProducer.php
More file actions
90 lines (72 loc) · 2.16 KB
/
Copy pathProducer.php
File metadata and controls
90 lines (72 loc) · 2.16 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
namespace Tests\Support\Helper;
use PhpAmqpLib\Channel\AMQPChannel;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;
class Producer implements \ADT\BackgroundQueue\Broker\Producer
{
public ?AMQPStreamConnection $connection = null;
public ?AMQPChannel $channel = null;
private array $initQueues = [];
public function publish(int $id, string $queue, ?int $expiration = null): void
{
$this->initQueue($queue);
$this->getChannel()->basic_publish(new AMQPMessage($id, $expiration ? ['expiration' => $expiration] : []), $queue, '', true);
$this->getChannel()->wait_for_pending_acks();
}
public function publishNoop(): void
{
}
public function consume()
{
$this->getChannel()->basic_get('general', true);
}
public function purge(string $queue): void
{
$this->initQueue($queue);
$this->getChannel()->queue_purge($queue);
}
public function getMessageCount(string $queue)
{
list(, $messageCount,) = $this->getChannel()->queue_declare($queue, true);
return $messageCount;
}
private function initQueue($queue)
{
if (isset($this->initQueues[$queue])) {
return;
}
$exchange = $queue = $queue ?: 'general';
$args = [];
if ($queue === 'waiting') {
$args = new AMQPTable([
'x-dead-letter-exchange' => 'general',
]);
}
$this->getChannel()->queue_declare($queue, false, true, false, false, false, $args);
$this->getChannel()->exchange_declare($exchange, 'direct', false, true, false);
$this->getChannel()->queue_bind($queue, $exchange);
$this->initQueues[$queue] = true;
}
private function getConnection(): AMQPStreamConnection
{
if (!$this->connection) {
$this->connection = new AMQPStreamConnection($_ENV['PROJECT_RABBITMQ_HOST'], $_ENV['PROJECT_RABBITMQ_PORT'], $_ENV['PROJECT_RABBITMQ_USER'], $_ENV['PROJECT_RABBITMQ_PASSWORD']);
}
return $this->connection;
}
private function getChannel(): AMQPChannel
{
if (!$this->channel) {
$this->channel = $this->getConnection()->channel();
$this->channel->confirm_select();
}
return $this->channel;
}
public function __destruct()
{
$this->channel->close();
$this->connection->close();
}
}