Skip to content

Commit 8f7a260

Browse files
committed
[rdkafka] Don't do unnecessary subscribe\unsubscribe on every receive call
1 parent b0fcee8 commit 8f7a260

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

pkg/rdkafka/RdKafkaConsumer.php

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,11 @@ public function getQueue()
8282
*/
8383
public function receive($timeout = 0)
8484
{
85-
$this->consumer->subscribe([$this->topic->getTopicName()]);
85+
if (false == $this->subscribed) {
86+
$this->consumer->subscribe([$this->topic->getTopicName()]);
87+
88+
$this->subscribed = true;
89+
}
8690

8791
$message = null;
8892
if ($timeout > 0) {
@@ -95,8 +99,6 @@ public function receive($timeout = 0)
9599
}
96100
}
97101

98-
$this->consumer->unsubscribe();
99-
100102
return $message;
101103
}
102104

pkg/rdkafka/RdKafkaContext.php

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,18 @@ class RdKafkaContext implements PsrContext
2929
*/
3030
private $producer;
3131

32+
/**
33+
* @var KafkaConsumer[]
34+
*/
35+
private $kafkaConsumers;
36+
3237
/**
3338
* @param array $config
3439
*/
3540
public function __construct(array $config)
3641
{
3742
$this->config = $config;
43+
$this->kafkaConsumers = [];
3844

3945
$this->setSerializer(new JsonSerializer());
4046
}
@@ -94,8 +100,10 @@ public function createConsumer(PsrDestination $destination)
94100
{
95101
InvalidDestinationException::assertDestinationInstanceOf($destination, RdKafkaTopic::class);
96102

103+
$this->kafkaConsumers[] = $kafkaConsumer = new KafkaConsumer($this->getConf());
104+
97105
$consumer = new RdKafkaConsumer(
98-
new KafkaConsumer($this->getConf()),
106+
$kafkaConsumer,
99107
$this,
100108
$destination,
101109
$this->getSerializer()
@@ -113,6 +121,12 @@ public function createConsumer(PsrDestination $destination)
113121
*/
114122
public function close()
115123
{
124+
$kafkaConsumers = $this->kafkaConsumers;
125+
$this->kafkaConsumers = [];
126+
127+
foreach ($kafkaConsumers as $kafkaConsumer) {
128+
$kafkaConsumer->unsubscribe();
129+
}
116130
}
117131

118132
/**

0 commit comments

Comments
 (0)