|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace LaravelTool\KafkaQueue\Kafka; |
| 4 | + |
| 5 | +use RdKafka\Conf as KafkaConfig; |
| 6 | +use RdKafka\Exception as KafkaException; |
| 7 | +use RdKafka\KafkaConsumer; |
| 8 | +use RdKafka\Message; |
| 9 | +use RuntimeException; |
| 10 | + |
| 11 | +class Consumer |
| 12 | +{ |
| 13 | + private KafkaConsumer $consumer; |
| 14 | + |
| 15 | + public function __construct( |
| 16 | + protected array $config |
| 17 | + ) { |
| 18 | + $this->consumer = new KafkaConsumer($this->generateConfig($config)); |
| 19 | + } |
| 20 | + |
| 21 | + public function consume(string $topic): ?Message |
| 22 | + { |
| 23 | + try { |
| 24 | + $this->checkSubscription($topic); |
| 25 | + |
| 26 | + $message = $this->consumer->consume($this->config['consumer_timeout_ms']); |
| 27 | + } catch (KafkaException) { |
| 28 | + return null; |
| 29 | + } |
| 30 | + |
| 31 | + return match ($message->err) { |
| 32 | + RD_KAFKA_RESP_ERR_NO_ERROR => $message, |
| 33 | + RD_KAFKA_RESP_ERR__PARTITION_EOF, RD_KAFKA_RESP_ERR__TIMED_OUT, RD_KAFKA_RESP_ERR__UNKNOWN_PARTITION, RD_KAFKA_RESP_ERR__UNKNOWN_TOPIC, RD_KAFKA_RESP_ERR_UNKNOWN_TOPIC_OR_PART => null, |
| 34 | + default => throw new RuntimeException($message->errstr(), $message->err), |
| 35 | + }; |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * @throws KafkaException |
| 40 | + */ |
| 41 | + public function commit():void |
| 42 | + { |
| 43 | + $this->consumer->commit(); |
| 44 | + } |
| 45 | + |
| 46 | + private function generateConfig(array $config): KafkaConfig |
| 47 | + { |
| 48 | + $kafkaConfig = new KafkaConfig(); |
| 49 | + $kafkaConfig->set('metadata.broker.list', $config['broker_list']); |
| 50 | + $kafkaConfig->set('group.id', $config['group_name']); |
| 51 | + $kafkaConfig->set('heartbeat.interval.ms', $config['heartbeat_ms']); |
| 52 | + $kafkaConfig->set('auto.offset.reset', 'earliest'); |
| 53 | + |
| 54 | + return $kafkaConfig; |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * @throws KafkaException |
| 59 | + */ |
| 60 | + private function checkSubscription(string $topic): void |
| 61 | + { |
| 62 | + if (!in_array($topic, $this->consumer->getSubscription())) { |
| 63 | + $this->consumer->subscribe([$topic]); |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments