This commit is contained in:
2020-10-28 16:04:52 +08:00
parent aae349efdd
commit f05e459be6
+20 -10
View File
@@ -37,6 +37,11 @@ class Producer extends Component
private string $_topic = ''; private string $_topic = '';
private Conf $conf;
private TopicConf $topicConf;
/** /**
* @param $servers * @param $servers
* @return Producer * @return Producer
@@ -45,9 +50,11 @@ class Producer extends Component
*/ */
public function setBrokers(string $servers) public function setBrokers(string $servers)
{ {
if (!$this->conf) {
/** @var Conf $conf */ /** @var Conf $conf */
$conf = Snowflake::createObject(Conf::class); $this->conf = Snowflake::createObject(Conf::class);
$conf->set('metadata.broker.list', $servers); }
$this->conf->set('metadata.broker.list', $servers);
return $this; return $this;
} }
@@ -60,10 +67,11 @@ class Producer extends Component
*/ */
public function setAck(bool $value) public function setAck(bool $value)
{ {
/** @var TopicConf $conf */ if (!$this->topicConf) {
$conf = Snowflake::createObject(TopicConf::class); /** @var Conf $conf */
$conf->set('request.required.acks', (int)$value); $this->topicConf = Snowflake::createObject(TopicConf::class);
}
$this->topicConf->set('request.required.acks', (int)$value);
return $this; return $this;
} }
@@ -87,16 +95,18 @@ class Producer extends Component
*/ */
public function delivery($message, $key = null, $timeout = 5) public function delivery($message, $key = null, $timeout = 5)
{ {
$conf = Snowflake::createObject(Conf::class); if (!$this->conf || !$this->topicConf) {
$conf->setDrmSgCb(function ($kafka, $message) { throw new \Exception('Error. Please set kafka conf.');
}
$this->conf->setDrmSgCb(function ($kafka, $message) {
// $this->debug(var_export($message, true)); // $this->debug(var_export($message, true));
}); });
$conf->setErrorCb(function ($kafka, $err, $reason) { $this->conf->setErrorCb(function ($kafka, $err, $reason) {
$this->error(sprintf("Kafka error: %s (reason: %s)", rd_kafka_err2str($err), $reason)); $this->error(sprintf("Kafka error: %s (reason: %s)", rd_kafka_err2str($err), $reason));
}); });
$rk = new \RdKafka\Producer(); $rk = new \RdKafka\Producer();
$topic = $rk->newTopic($this->_topic, Snowflake::createObject(TopicConf::class)); $topic = $rk->newTopic($this->_topic, $this->topicConf);
$topic->produce(RD_KAFKA_PARTITION_UA, 0, $message, $key); $topic->produce(RD_KAFKA_PARTITION_UA, 0, $message, $key);
if ($rk->getOutQLen() > 0) { if ($rk->getOutQLen() > 0) {
$rk->poll($timeout); $rk->poll($timeout);