C++ KAFKA demo
时间: 2023-10-23 18:09:28 浏览: 185
c_rdkfk.zip
以下是一个简单的 C++ Kafka 生产者示例代码:
```cpp
#include <iostream>
#include <string>
#include <librdkafka/rdkafkacpp.h>
int main() {
std::string brokers = "localhost:9092";
std::string topic_name = "test_topic";
RdKafka::Conf *conf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);
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;
}
RdKafka::Producer *producer = RdKafka::Producer::create(conf, errstr);
if (!producer) {
std::cerr << "Failed to create producer: " << errstr << std::endl;
delete conf;
return 1;
}
RdKafka::Topic *topic = RdKafka::Topic::create(producer, topic_name, nullptr, errstr);
if (!topic) {
std::cerr << "Failed to create topic: " << errstr << std::endl;
delete producer;
delete conf;
return 1;
}
std::string message_str = "Hello, Kafka!";
RdKafka::ErrorCode resp = producer->produce(topic, RdKafka::Topic::PARTITION_UA,
RdKafka::Producer::RK_MSG_COPY,
const_cast<char *>(message_str.c_str()),
message_str.size(),
nullptr, nullptr);
if (resp != RdKafka::ERR_NO_ERROR) {
std::cerr << "Failed to produce message: " << RdKafka::err2str(resp) << std::endl;
} else {
std::cout << "Produced message: " << message_str << std::endl;
}
producer->flush(1000);
delete topic;
delete producer;
delete conf;
return 0;
}
```
这个示例代码使用了 librdkafka 库,需要在编译时链接该库。在 Ubuntu 系统上,可以使用以下命令安装该库:
```
sudo apt-get install librdkafka-dev
```
阅读全文