#安裝Kafka 服務
直接到kafka 官網, 下載最新的
wget https://mirror.bit.edu.cn/apache/kafka/2.5.0/kafka_2.13-2.5.0.tgz
解壓縮,進入目錄
tar -zxvf kafka_2.13-2.5.0.tgz cd kafka_2.13-2.5.0
啟動Kafka 服務
使用安裝套件中的腳本啟動單節點Zookeeper 實例
bin/zookeeper-server-start.sh -daemon config/zookeeper.properties
使用kafka -server-start.sh 啟動kafka 服務
bin/kafka-server-start.sh config/server.properties
建立topic
#bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic test
查看topic 列表,檢查是否建立成功##
bin/kafka-topics.sh --list --zookeeper localhost:2181 $ test生產者,發送訊息
bin/kafka-console-producer.sh --broker-list 127.0.0.1:9092 --topic test服務方面到這裡就差不多了,接下來就是php 的事了。
安裝PHP 擴充功能
rdkafka 安裝需要依賴librdkafka , 所以先安裝librdkafkagit clone https://github.com/edenhill/librdkafka.git cd librdkafka ./configure make && make install安裝php-rdkafka 擴充功能
git clone https://github.com/arnaud-lb/php-rdkafka.git cd php-rdkafka phpize ./configure --with-php-config=/usr/local/Cellar/php@7.2/7.2.24/bin/php-config ## 这里根据自己的情况填写路径 make && make install在php-ini 加上
extension=rdkafka.so重啟,php-fpm,就應該可以看到該擴充。
使用Kafka
建立一個生產者類別<?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('metadata.broker.list', 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('auto.commit.interval.ms', 100); $topicConf->set('offset.store.method', 'broker'); $topicConf->set('auto.offset.reset', '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; } } } }
問題總和
1、 No Java runtime present, requesting install因為kafka 需要java 環境支持,所以安裝java 環境。可以到javase-jdk14-downloads 選擇自己的版本進行下載安裝2、創建topic 出現:Replication factor: 1 larger than available brokers: 0#意思是至少有一個brokers. 也就是說沒有有效的brokers 可以用。你要確保你的 kafka 已經啟動了推薦教學:《PHP教學》
以上是PHP 訊息隊列 Kafka 使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!