本文主要和大家分享linux下php扩展kafka的实例,希望能帮助到大家。
1、安装librdkafka
wget <a rel="nofollow" href="https://github.com/edenhill/librdkafka/archive/master.zip"target="_blank">https://github.com/edenhill/librdkafka/archive/master.zip</a> #下载 mv master.zip librdkafka-master.zip #修改包名 unzip librdkafka-master.zip #解压 cd librdkafka-master #进入安装文件夹 ./configure #配置 make #编译 make install #安装
2、安装phpkafka
cd /usr/local/src #进入安装包存放目录 wget <a rel="nofollow" href="https://github.com/EVODelavega/phpkafka/archive/master.zip" target="_blank">https://github.com/EVODelavega/phpkafka/archive/master.zip</a> #下载 mv master.zip phpkafka-master.zip #修改包名 unzip phpkafka-master.zip #解压 cd phpkafka-master #进入安装文件夹 /usr/local/php/bin/phpize #加载php扩展模块 ./configure --enable-kafka --with-php-config=/usr/local/php/bin/php-config #配置 make #编译 make install #安装 3、修改php配置文件 vi /usr/local/php/etc/php.ini
打开php配置文件,在最后一行添加下面的代码
extension="kafka.so"
:wq! #保存退出
4、测试
以下代码,保存为phpinfo.php
<?php phpinfo(); ?>
有kafka模块
这是生产者
$kafka = new Kafka("localhost:9092"); $partitions = $kafka->getPartitionsForTopic('testkk'); $in = fopen('php://stdin', 'r'); while (true) { echo "\nEnter comma separated messages:\n"; $messages = explode(',', fgets($in)); foreach (array_keys($messages) as $k) { //$messages[$k] = trim($messages[$k]); } $bytes=$kafka->produce("testkk", "kkkkkkk"); printf("\nSuccessfully sent %d messages (%d bytes)\n\n", count($messages), $bytes); }