在Windows下通过C++代码在librdkafka中使用Kafka的Producer API,可以按照以下步骤进行:
#include <iostream>
#include <string>
#include <librdkafka/rdkafkacpp.h>
int main() {
std::string brokers = "kafka_broker1:9092,kafka_broker2:9092"; // Kafka集群地址和端口号
std::string topic = "test_topic"; // Kafka主题
// 创建Kafka配置对象
RdKafka::Conf *conf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);
// 设置Kafka集群地址和端口号
std::string errstr;
if (conf->set("bootstrap.servers", brokers, errstr) != RdKafka::Conf::CONF_OK) {
std::cerr << "Failed to set broker list: " << errstr << std::endl;
delete conf;
return 1;
}
// 创建Kafka Producer对象
RdKafka::Producer *producer = RdKafka::Producer::create(conf, errstr);
if (!producer) {
std::cerr << "Failed to create producer: " << errstr << std::endl;
delete conf;
return 1;
}
// 发送消息
std::string message = "Hello, Kafka!";
RdKafka::ErrorCode resp = producer->produce(topic, RdKafka::Topic::PARTITION_UA,
RdKafka::Producer::RK_MSG_COPY,
const_cast<char *>(message.c_str()),
message.size(),
NULL, NULL);
if (resp != RdKafka::ERR_NO_ERROR) {
std::cerr << "Failed to produce message: " << RdKafka::err2str(resp) << std::endl;
}
// 等待消息发送完成
producer->flush(1000);
// 释放资源
delete producer;
delete conf;
return 0;
}
g++ -o kafka_producer kafka_producer.cpp -lrdkafka
./kafka_producer
以上代码示例了如何使用librdkafka库在Windows下通过C++代码使用Kafka的Producer API。你可以根据实际需求进行修改和扩展。另外,腾讯云也提供了Kafka相关的产品和服务,你可以参考腾讯云的Kafka产品介绍了解更多信息。
领取专属 10元无门槛券
手把手带您无忧上云