温馨提示×

PHP rdkafka怎样发送消息

PHP
小樊
83
2024-11-24 07:45:45
栏目: 编程语言

要使用 PHP 的 RdKafka 扩展发送消息,首先确保已经正确安装并配置了 RdKafka

  1. 创建一个生产者实例:
<?php
$conf = new \RdKafka\Conf();
$producer = new \RdKafka\Producer($conf);
  1. 配置 Kafka 集群:
<?php
$conf->set('bootstrap.servers', 'your_kafka_broker1:9092,your_kafka_broker2:9092');
$conf->set('message.timeout.ms', '5000');
$conf->set('delivery.timeout.ms', '120000');
$conf->set('retry.backoff.ms', '1000');
  1. 将 Kafka 生产者与主题关联:
<?php
$producer->addBrokers("your_kafka_broker1:9092,your_kafka_broker2:9092");
$producer->subject_partition_list = "my_topic:0";
  1. 发送消息:
<?php
$topic = "my_topic";
$message = "Hello, World!";
$key = ""; // 如果需要设置消息的键,可以在这里设置

$producer->send([
    [
        'topic' => $topic,
        'value' => $message,
        'key' => $key,
    ],
]);
  1. 检查发送结果:
<?php
$result = $producer->flush();
if ($result === RD_KAFKA_RESP_ERR) {
    echo "Error sending message: " . $producer->errstr() . "\n";
} else {
    echo "Message sent successfully\n";
}
  1. 关闭生产者:
<?php
$producer->close();

将以上代码片段组合在一起,即可使用 PHP 的 RdKafka 扩展发送消息。请确保替换 your_kafka_brokermy_topic 为实际的 Kafka 代理地址和主题名称。

0