I want create a topic with kafka-php programming library.
https://github.com/weiboad/kafka-php
How can I do?
If topic doesn't exist in kafka server, executing this code, it doesn't work. It doesn't insert 10 messages "test1....message." because topic isn't create.
date_default_timezone_set('PRC');
// Create the logger
$logger = new Logger('my_logger');
// Now add some handlers
$logger->pushHandler(new StreamHandler(DIR . '/app.log', Logger::DEBUG));
$config = \Kafka\ProducerConfig::getInstance();
$config->setMetadataRefreshIntervalMs(10000);
$config->setMetadataBrokerList('127.0.0.1:9092');
$config->setBrokerVersion('1.0.0');
$config->setRequiredAck(1);
$config->setIsAsyn(false);
$config->setProduceInterval(500);
$producer = new \Kafka\Producer();
$producer->setLogger($logger);
for($i = 0; $i < 10; $i++) {
$result = $producer->send([
[
'topic' => 'test1',
'value' => 'test1....message.',
'key' => ''
]
]);
}
My Answer:
To create a topic using the kafka-php programming library, you can follow these steps:
1. Install the kafka-php library by adding it to your project's dependencies using Composer. You can do this by running the following command in your project directory:
composer require weiboad/kafka-php
2. Use the following code snippet to create a topic and insert 10 messages into it:
php
require 'vendor/autoload.php';
use Kafka\Producer;
use Kafka\ProducerConfig;
$config = ProducerConfig::getInstance();
$config->setMetadataRefreshIntervalMs(10000);
$config->setMetadataBrokerList('localhost:9092');
$config->setBrokerVersion('1.0.0');
$config->setRequiredAck(-1);
$config->setIsAsyn(false);
$config->setProduceInterval(500);
$producer = new Producer();
$producer->send([
[
'topic' => 'your_topic_name',
'value' => 'your_message',
],
]);
echo "Messages sent successfully\n";
Make sure to replace `'localhost:9092'` with the address of your Kafka server and `'your_topic_name'` with the name of the topic you want to create. You can also customize the message content by changing `'your_message'`.
If the topic does not exist on the Kafka server, the library should automatically create it when you try to send messages to it. If the code is not working as expected, make sure that your Kafka server is running and accessible, and that the topic name and server address are correct.
I hope this helps! Let me know if you have any other questions.
Rate this post
4 of 5 based on 4651 votesComments