要開始使用php rdkafka,首先需要安裝rdkafka擴展。可以通過以下命令使用pecl來安裝:
pecl install rdkafka
安裝完成后,在php.ini文件中添加以下內容來啟用rdkafka擴展:
extension=rdkafka.so
然后可以在PHP代碼中使用rdkafka擴展來編寫Kafka生產者和消費者。以下是一個簡單的示例:
<?php
$conf = new RdKafka\Conf();
$conf->set('metadata.broker.list', 'localhost:9092');
$producer = new RdKafka\Producer($conf);
$producer->addBrokers('localhost:9092');
$topic = $producer->newTopic('test');
for ($i = 0; $i < 10; $i++) {
$topic->produce(RD_KAFKA_PARTITION_UA, 0, 'Message ' . $i);
}
$producer->poll(0);
while ($producer->getOutQLen() > 0) {
$producer->poll(50);
}
echo "Messages sent successfully\n";
$consumer = new RdKafka\Consumer($conf);
$consumer->addBrokers('localhost:9092');
$topic = $consumer->newTopic('test');
$topic->consumeStart(0, RD_KAFKA_OFFSET_BEGINNING);
while (true) {
$message = $topic->consume(0, 1000);
if ($message->err) {
echo "Error: {$message->errstr()}\n";
break;
} else {
echo "Message: {$message->payload}\n";
}
}
$consumer->consumeStop(0);
這是一個簡單的示例,它創建了一個Kafka生產者來發送消息,并創建一個Kafka消費者來接收消息。您可以根據自己的需求進一步擴展和定制這段代碼。