php处理kafka消息

如果安装kafka,看上一篇文章CentOS7安装kafka

php如果要使用kafka的话,需要安装一下kafka-php:

# composer require nmred/kafka-php

kafka-php的GitHub地址

先写一个kafka_producer.php,用来做为生产者:


require '/var/www/extend/vendor/autoload.php';

$config = \Kafka\ProducerConfig::getInstance();
// 指定kafka broker列表,有多个的话用逗号分隔
$config->setMetadataBrokerList('localhost:9092');

$producer = new \Kafka\Producer(
    function() {
        return [
            [
                'topic' => 'test',
                'value' => 'test....message4.',
            ],
        ];                                                    
    }
);
$producer->success(function($result) {
            var_dump($result);
            });
$producer->error(function($errorCode) {
                var_dump($errorCode);
                });
$producer->send(true);

然后,再写一个kafka_consumer.php,用来做为消费者:


require '/var/www/extend/vendor/autoload.php';

$config = \Kafka\ConsumerConfig::getInstance();
$config->setMetadataBrokerList('localhost:9092');
// 消费模块的分组ID
$config->setGroupId('haha');
// 将要消费的kafka topic名称
$config->setTopics(['test']);
// 如果消费offset失效的时候重置offset的策略
$config->setOffsetReset('latest');

$consumer = new \Kafka\Consumer();
$consumer->start(function($topic, $part, $message) {
    var_dump($message);
});

下面,先启动kafka_consumer:

# php kafka_consumer.php

切换另一个终端窗口,启动kafka_producer:

# php kafka_producer.php 

现在,返回执行kafka_consumer的终端窗口,会发现经收到了消息:

array(3) {
  ["offset"]=>
  int(16)
  ["size"]=>
  int(39)
  ["message"]=>
  array(6) {
    ["crc"]=>
    int(3041764187)
    ["magic"]=>
    int(1)
    ["attr"]=>
    int(0)
    ["timestamp"]=>
    int(-1)
    ["key"]=>
    string(0) ""
    ["value"]=>
    string(17) "test....message4."
  }
}

你可能感兴趣的:(PHP,kafka)