在PHP中使用Kafka可以通過使用Kafka PHP客戶端庫來實現。以下是一些用法示例:
<?php
require('vendor/autoload.php');
$producer = new RdKafka\Producer();
$producer->setLogLevel(LOG_DEBUG);
$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);
}
<?php
require('vendor/autoload.php');
$consumer = new RdKafka\Consumer();
$consumer->setLogLevel(LOG_DEBUG);
$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";
}
}
這些是使用Kafka在PHP中實現生產者和消費者的一些示例。在實際應用中,可以根據具體需求進一步定制和擴展。