Home > Article > Backend Development > Kafka client written in PHP
Kafka-php uses a kafka client written in pure PHP. It currently supports versions of Kafka 0.8.x or above. The project v0.2.x is not compatible with v0.1.x. If you use the original v0.1 For .x, you can refer to the document Kafka PHP v0.1.x Document, but it is recommended to switch to v0.2.x. v0.2.x uses PHP asynchronous execution to interact with kafka broker, which is more stable and efficient than v0.1.x. Since it is written in PHP language, it can be used without compiling any extensions, which reduces access and maintenance costs.
PHP version is greater than 5.5
Kafka Server version is greater than 0.8.0
The consumption module Kafka Server version needs to be greater than 0.9.0
Add composer to depend on nmred/kafka -php to the composer.json file of the project, such as:
{ "require": { "nmred/kafka-php": "0.2.*" } }
<?php require '../vendor/autoload.php'; date_default_timezone_set('PRC'); use Monolog\Logger; use Monolog\Handler\StdoutHandler; // Create the logger $logger = new Logger('my_logger'); // Now add some handlers $logger->pushHandler(new StdoutHandler()); // 设置生产相关配置,具体配置参数见 [Configuration](Configuration.md) $config = \Kafka\ProducerConfig::getInstance(); $config->setMetadataRefreshIntervalMs(10000); $config->setMetadataBrokerList('10.13.4.159:9192'); $config->setBrokerVersion('0.9.0.1'); $config->setRequiredAck(1); $config->setIsAsyn(false); $config->setProduceInterval(500); $producer = new \Kafka\Producer(function() { return array( array( 'topic' => 'test', 'value' => 'test....message.', 'key' => 'testkey', ), ); }); $producer->setLogger($logger); $producer->success(function($result) { var_dump($result); }); $producer->error(function($errorCode, $context) { var_dump($errorCode); }); $producer->send();
<?php require '../vendor/autoload.php'; date_default_timezone_set('PRC'); use Monolog\Logger; use Monolog\Handler\StdoutHandler; // Create the logger $logger = new Logger('my_logger'); // Now add some handlers $logger->pushHandler(new StdoutHandler()); $config = \Kafka\ConsumerConfig::getInstance(); $config->setMetadataRefreshIntervalMs(10000); $config->setMetadataBrokerList('10.13.4.159:9192'); $config->setGroupId('test'); $config->setBrokerVersion('0.9.0.1'); $config->setTopics(array('test')); //$config->setOffsetReset('earliest'); $consumer = new \Kafka\Consumer(); $consumer->setLogger($logger); $consumer->start(function($topic, $part, $message) { var_dump($message); });
The above content is a Kafka client tutorial written in PHP. I hope it can help everyone.
Related recommendations:
Example of handshake between client and server in Socket in python
php gets the visitor (client) IP and geographical location text tutorial
How to quickly develop a webservice client?
The above is the detailed content of Kafka client written in PHP. For more information, please follow other related articles on the PHP Chinese website!