php-pubsub-kafka
A Kafka adapter for the php-pubsub package., (*1)
, (*2)
Installation
-
Install librdkafka c library, (*3)
$ cd /tmp
$ mkdir librdkafka
$ cd librdkafka
$ git clone https://github.com/edenhill/librdkafka.git .
$ ./configure
$ make
$ make install
-
Install the php-rdkafka PECL extension, (*4)
PHP5, (*5)
$ pecl install channel://pecl.php.net/rdkafka-1.0.0
PHP7, (*6)
$ pecl install channel://pecl.php.net/rdkafka-beta
-
Add the following to your php.ini file to enable the php-rdkafka extension
extension=rdkafka.so, (*7)
-
composer require superbalist/php-pubsub-kafka, (*8)
Usage
// create consumer
$topicConf = new \RdKafka\TopicConf();
$topicConf->set('auto.offset.reset', 'smallest');
$conf = new \RdKafka\Conf();
$conf->set('group.id', 'php-pubsub');
$conf->set('metadata.broker.list', '127.0.0.1');
$conf->set('enable.auto.commit', 'false');
$conf->set('offset.store.method', 'broker');
$conf->setDefaultTopicConf($topicConf);
$consumer = new \RdKafka\KafkaConsumer($conf);
// create producer
$producer = new \RdKafka\Producer();
$producer->addBrokers('127.0.0.1');
$adapter = new \Superbalist\PubSub\Kafka\KafkaPubSubAdapter($producer, $consumer);
// consume messages
// note: this is a blocking call
$adapter->subscribe('my_channel', function ($message) {
var_dump($message);
});
// publish messages
$adapter->publish('my_channel', 'HELLO WORLD');
$adapter->publish('my_channel', json_encode(['hello' => 'world']));
$adapter->publish('my_channel', 1);
$adapter->publish('my_channel', false);
Examples
The library comes with examples for the adapter and a Dockerfile for
running the example scripts., (*9)
Run make up., (*10)
You will start at a bash prompt in the /opt/php-pubsub directory., (*11)
If you need another shell to publish a message to a blocking consumer, you can run docker-compose run php-pubsub-kafka /bin/bash, (*12)
To run the examples:, (*13)
$ php examples/KafkaConsumerExample.php
$ php examples/KafkaPublishExample.php (in a separate shell)