What is the usage of Kafka in PHP?
Using Kafka in PHP can be achieved by using the Kafka PHP client library. Here are some usage examples:
- Producer: Using a Kafka producer in PHP allows you to send messages to a Kafka . This can be done using the Producer class in the Kafka PHP client library. Here is an example code:
<?php
require('vendor/autoload.php');
$producer = new RdKafka\Producer();
$producer->setLogLevel(LOG_DEBUG);
$producer->addBrokers('localhost:9092');
$topic = $producer->newTopic('test');
for ($i = 0; $i < 10; $i++) {
$topic->produce(RD_KAFKA_PARTITION_UA, 0, 'Message ' . $i);
}
$producer->poll(0);
while ($producer->getOutQLen() > 0) {
$producer->poll(50);
}
- Consumer: In PHP, consumers can suribe to messages from a Kafka and process them using the Consumer class from the Kafka PHP client library. Below is an example code.
<?php
require('vendor/autoload.php');
$consumer = new RdKafka\Consumer();
$consumer->setLogLevel(LOG_DEBUG);
$consumer->addBrokers('localhost:9092');
$topic = $consumer->newTopic('test');
$topic->consumeStart(0, RD_KAFKA_OFFSET_BEGINNING);
while (true) {
$message = $topic->consume(0, 1000);
if ($message->err) {
echo "Error: {$message->errstr()}\n";
break;
} else {
echo "Message: {$message->payload}\n";
}
}
These are some examples of implementing producers and consumers in PHP using Kafka. In real applications, they can be ized and expanded according to specific needs.
More tutorials
How does the Kafka Producer handle message sending failures?(Opens in a new browser tab)
How to retrieve the request type of an input value in PHP?(Opens in a new browser tab)
How to check if an array is not empty in PHP?(Opens in a new browser tab)
What is the purpose of the intval function in PHP?(Opens in a new browser tab)
How are Kafka message logs stored?(Opens in a new browser tab)