PHP Kafka client ------ php-rdkafka

 Install PHP reference: https://blog.csdn.net/abcdu1/article/details/112317578

1. Install librdkafka

(1) Download

https://github.com/edenhill/librdkafka

(2) Decompression configuration

tar -zxvf librdkafka.tar.gz
cd librdkafka/
./configure

(3) Compile and install

make && make install

 

2. Install php-rdkafka

(1) Download

https://github.com/arnaud-lb/php-rdkafka

(2) Decompression configuration

You must install PHP to execute the phpize command, install PHP reference

tar -zxvf  php-rdkafka.tar.gz
cd php-rdkafka/
phpize
./configure

(3) Compile and install

make all -j 5
sudo make install

(4) Configure the php.ini file

Open php.ini and add 

extension=rdkafka.so

(5) Installation test

php -i | grep rdkafka

 

3. Code example running

(1) Code example

Create a new file producer.php, copy the following code into it, and modify the following two lines:

$conf->set('metadata.broker.list','localhost:9092'); //Modify the broker address you established

$topic = $producer->newTopic("test"); //Modify the topic created for yourself

<?php

$conf = new RdKafka\Conf();
$conf->set('metadata.broker.list', 'localhost:9092');

//If you need to produce exactly once and want to keep the original produce order, uncomment the line below
//$conf->set('enable.idempotence', 'true');

$producer = new RdKafka\Producer($conf);

$topic = $producer->newTopic("test");

for ($i = 0; $i < 10; $i++) {
    $topic->produce(RD_KAFKA_PARTITION_UA, 0, "Message $i");
    $producer->poll(0);
}

for ($flushRetries = 0; $flushRetries < 10; $flushRetries++) {
    $result = $producer->flush(10000);
    if (RD_KAFKA_RESP_ERR_NO_ERROR === $result) {
        break;
    }
}

if (RD_KAFKA_RESP_ERR_NO_ERROR !== $result) {
    throw new \RuntimeException('Was unable to flush, messages might be lost!');
}

?>

(2) Run test

 After saving the file, run

php producer.php 

You can see that the message is pushed into the corresponding topic of Kafka.

 

reference:

https://github.com/edenhill/librdkafka

https://github.com/arnaud-lb/php-rdkafka

https://arnaud.le-blanc.net/php-rdkafka-doc/phpdoc/rdkafka.examples-producer.html

https://arnaud.le-blanc.net/php-rdkafka-doc/phpdoc/rdkafka.installation.manual.html

https://arnaud.le-blanc.net/php-rdkafka-doc/phpdoc/rdkafka.installation.windows.html

Guess you like

Origin blog.csdn.net/abcdu1/article/details/112349810