在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中实现生产者和消费者的一些示例。在实际应用中,可以根据具体需求进一步定制和扩展。