已在phpinfo确认rdkafka已开启拓展。
但如下报错:提示必须配置 group . id :
Fatal error : Uncaught RdKafka \ Exception :" g roup . id " must be configured in E :\ phpstudy_proWWWmattest . phpl O Stack trace :#O E : phpstudy_proWWWmattest . php ( I O ): R dKafka \ KafkaConsumer-) construct ( Objec t ( RdKafka \ Conf ))#l ( main ) t hrown in E :\ php study_proWWWmattest . php on line I O
<?php
// Kafka服务器和Topic信息
$brokers = "n9-kkt.test001.com:30902";
$topic = "test.info.tst";
// 创建Kafka消费者实例
$conf = new RdKafka\Conf();
$conf->set('metadata.broker.list', $brokers);
$consumer = new RdKafka\KafkaConsumer($conf);
// 订阅Topic
$consumer->subscribe([$topic]);
// 从Topic中读取消息
while (true) {
$message = $consumer->consume(120 * 1000); // 超时时间为2分钟
switch ($message->err) {
case RD_KAFKA_RESP_ERR_NO_ERROR:
// 消费成功
$payload = $message->payload;
$json = json_encode($payload, JSON_UNESCAPED_UNICODE);
echo $json;
break;
case RD_KAFKA_RESP_ERR__PARTITION_EOF:
// 已经到达分区末尾
break;
case RD_KAFKA_RESP_ERR__TIMED_OUT:
// 超时等待消息
break;
default:
// 其他错误
echo "消费失败: " . $message->errstr() . "\n";
break;
}
}
// 关闭Kafka消费者
$consumer->close();