要使用 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 代理地址和主題名稱。