1.安装Kafka服务
直接去卡帕官网下载最新的。
Wget
解压进入目录
Tar -zxvf ka
Cd卡
开始使用
A.Kafka服务启动
使用安装包中的脚本启动单节点Zookeeper实例
BIN-DAEMON COFIG
使用Ka启动Kafka服务
Bin/ka config
创建主题
bin-create-zookeeper localhost :2181-replication-factor 1-partitions 1-topic test
查看Topic列表以验证是否已成功创建
bin-list-zookeeper localhost :2181
$ test
生产者,发送消息
bin-broker-list 127 . 0 . 0 . 1:9092-topic test
服务方面到这里就差不多了,接下来是PHP的事。
2. 安装 PHP 扩展
rdkafka 安装需要依赖 librdkafka , 所以先安装 librdkafka
git clone
cd librdkafka
./configure
make && make install
安装 php-rdkafka 扩展
git clone
cd php-rdkafka
phpize
./configure --with-php-config=/usr/local/Cellar/php@7.2 ## 这里根据自己的情况填写路径
make && make install
在 php-ini 加上
extension=rdka
重启,php-fpm,就应该可以看到该扩展。
3. 使用
创建一个生产者类
<?php
class KafkaProducer
{
public static $brokerList = '127.0.0.1:9092';
public static function send($message, $topic)
{
self::producer($message, $topic);
}
public static function producer($message, $topic = 'test')
{
$conf = new \RdKafka\Conf();
$conf->set('me;, self::$brokerList);
$producer = new \RdKafka\Producer($conf);
$topic = $producer->newTopic($topic);
$topic->produce(RD_KAFKA_PARTITION_UA, 0, json_encode($message));
$producer->poll(0);
$result = $producer->flush(10000);
if (RD_KAFKA_RESP_ERR_NO_ERROR !== $result) {
throw new \RuntimeException('Was unable to flush, messages might be lost!');
}
}
}
创建一个消费类
<?php
class KafkaConsumer
{
public static $brokerList = '127.0.0.1:9092';
public static function consumer()
{
$conf = new \RdKafka\Conf();
$conf->set('group.id', 'test');
$rk = new \RdKafka\Consumer($conf);
$rk->addBrokers("127.0.0.1");
$topicConf = new \RdKafka\TopicConf();
$topicConf->set('au;, 100);
$topicConf->set('o;, 'broker');
$topicConf->set('au;, 'smallest');
$topic = $rk->newTopic('test', $topicConf);
$topic->consumeStart(0, RD_KAFKA_OFFSET_STORED);
while (true) {
$message = $topic->consume(0, 120*10000);
switch ($message->err) {
case RD_KAFKA_RESP_ERR_NO_ERROR:
var_dump($message);
break;
case RD_KAFKA_RESP_ERR__PARTITION_EOF:
echo "No more messages; will wait for more\n";
break;
case RD_KAFKA_RESP_ERR__TIMED_OUT:
echo "Timed out\n";
break;
default:
throw new \Exception($message->errstr(), $message->err);
break;
}
}
}
}
问题汇总
a. No Java runtime present, requesting install
因为 kafka 需要 java 环境支持,所以安装 java 环境。可以到 javase-jdk14-downloads 选择自己的版本进行下载安装
b. 创建 topic 出现:Replication factor: 1 larger than available brokers: 0
意思是至少有一个 brokers. 也就是说并没有有效的 brokers 可以用。你要确保你的 kafka 已经启动了