From 625f6c7b07da45abb7d8bc625813c6f695f6b890 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mr=C2=B7x?= Date: Fri, 30 Oct 2020 11:35:17 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=B9=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Kafka/Producer.php | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/Kafka/Producer.php b/Kafka/Producer.php index 41e6cfea..3e1b7918 100644 --- a/Kafka/Producer.php +++ b/Kafka/Producer.php @@ -3,6 +3,7 @@ declare(strict_types=1); namespace Kafka; +use Exception; use RdKafka\Conf; use RdKafka\TopicConf; use ReflectionException; @@ -75,11 +76,12 @@ class Producer extends Component * @throws NotFindClassException * @throws ReflectionException * @throws ComponentException + * @throws Exception */ public function delivery($message, $key = null, $isAck = false) { if (!$this->conf || !$this->topicConf) { - throw new \Exception('Error. Please set kafka conf.'); + throw new Exception('Error. Please set kafka conf.'); } $this->conf->setErrorCb(function ($kafka, $err, $reason) { $this->error(sprintf("Kafka error: %s (reason: %s)", rd_kafka_err2str($err), $reason)); @@ -92,20 +94,35 @@ class Producer extends Component $this->producer = Snowflake::createObject(\RdKafka\Producer::class, [$this->conf]); } + $this->setTopicAcks($isAck); + $this->push($message, $key); + } + + + private function push($message, $key) + { + $topic = $this->producer->newTopic($this->_topic, $this->topicConf); + $topic->produce(RD_KAFKA_PARTITION_UA, 0, $message, $key); + $this->producer->poll(0); + } + + + /** + * @param $isAck + */ + private function setTopicAcks(bool $isAck) + { if ($isAck) { - if ($this->producer->getOutQLen()>0) { + if ($this->producer->getOutQLen() > 0) { $this->flush(); } $this->topicConf->set('request.required.acks', '1'); } else { $this->topicConf->set('request.required.acks', '0'); } - - $topic = $this->producer->newTopic($this->_topic, $this->topicConf); - $topic->produce(RD_KAFKA_PARTITION_UA, 0, $message, $key); - $this->producer->poll(0); } + public function flush() { while ($this->producer->getOutQLen() > 0) {