要使用 PHP 的 RdKafka 扩展发送消息,首先确保已经正确安装并配置了 RdKafka
- 创建一个生产者实例:
- 配置 Kafka 集群:
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');
- 将 Kafka 生产者与主题关联:
addBrokers("your_kafka_broker1:9092,your_kafka_broker2:9092"); $producer->subject_partition_list = "my_topic:0";
- 发送消息:
send([ [ 'topic' => $topic, 'value' => $message, 'key' => $key, ], ]);
- 检查发送结果:
flush(); if ($result === RD_KAFKA_RESP_ERR) { echo "Error sending message: " . $producer->errstr() . "\n"; } else { echo "Message sent successfully\n"; }
- 关闭生产者:
close();将以上代码片段组合在一起,即可使用 PHP 的 RdKafka 扩展发送消息。请确保替换
your_kafka_broker
和my_topic
为实际的 Kafka 代理地址和主题名称。