要使用 PHP 的 RdKafka 扩展发送消息,首先确保已经正确安装并配置了 RdKafka
<?php
$conf = new \RdKafka\Conf();
$producer = new \RdKafka\Producer($conf);
<?php
$conf->set('bootstrap.servers', 'your_kafka_broker1:9092,your_kafka_broker2:9092');
$conf->set('message.timeout.ms', '5000');
$conf->set('delivery.timeout.ms', '120000');
$conf->set('retry.backoff.ms', '1000');
<?php
$producer->addBrokers("your_kafka_broker1:9092,your_kafka_broker2:9092");
$producer->subject_partition_list = "my_topic:0";
<?php
$topic = "my_topic";
$message = "Hello, World!";
$key = ""; // 如果需要设置消息的键,可以在这里设置
$producer->send([
[
'topic' => $topic,
'value' => $message,
'key' => $key,
],
]);
<?php
$result = $producer->flush();
if ($result === RD_KAFKA_RESP_ERR) {
echo "Error sending message: " . $producer->errstr() . "\n";
} else {
echo "Message sent successfully\n";
}
<?php
$producer->close();
将以上代码片段组合在一起,即可使用 PHP 的 RdKafka 扩展发送消息。请确保替换 your_kafka_broker
和 my_topic
为实际的 Kafka 代理地址和主题名称。