用C++写kafka运行的基本代码
时间: 2024-04-16 13:26:50 浏览: 181
以下是使用C++编写基本的Kafka运行代码的示例:
```cpp
#include <iostream>
#include <librdkafka/rdkafkacpp.h>
int main() {
std::string brokers = "localhost:9092"; // Kafka broker地址
std::string topic = "test_topic"; // Kafka主题名称
// 创建配置对象
RdKafka::Conf *conf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);
std::string errstr;
// 设置broker地址
if (conf->set("bootstrap.servers", brokers, errstr) != RdKafka::Conf::CONF_OK) {
std::cerr << "Failed to set broker address: " << errstr << std::endl;
delete conf;
return 1;
}
// 创建生产者对象
RdKafka::Producer *producer = RdKafka::Producer::create(conf, errstr);
if (!producer) {
std::cerr << "Failed to create kafka producer: " << errstr << std::endl;
delete conf;
return 1;
}
// 构造消息
std::string message = "Hello, Kafka!";
RdKafka::ProducerRecord *record = new RdKafka::ProducerRecord(topic, RdKafka::Topic::PARTITION_UA, RdKafka::ProducerRecord::COPY, &message[0], message.size());
// 发送消息
RdKafka::ErrorCode resp = producer->produce(record);
if (resp != RdKafka::ERR_NO_ERROR) {
std::cerr << "Failed to produce message: " << RdKafka::err2str(resp) << std::endl;
delete record;
delete producer;
delete conf;
return 1;
}
// 等待消息发送完成
producer->flush(10000);
// 释放资源
delete record;
delete producer;
delete conf;
std::cout << "Message sent to Kafka successfully!" << std::endl;
return 0;
}
```
上述代码示例使用librdkafka库,它是Kafka的一个C/C++客户端库。代码中创建了一个生产者对象,设置了Kafka broker地址和主题名称,然后发送一条消息到Kafka。请注意,你需要在编译和链接过程中添加librdkafka库的依赖。
这只是一个简单示例,你可以根据实际需求进行修改和扩展,例如添加消费者对象、订阅主题、处理消息等。记得在使用Kafka时,确保正确配置Kafka broker地址和主题名称,并根据需要进行错误处理和资源释放。
阅读全文