在C++中使用Kafka可以通過librdkafka庫實現。下面是一個簡單的示例代碼:
#include <librdkafka/rdkafkacpp.h>
#include <iostream>
int main() {
std::string brokers = "localhost:9092";
std::string topic = "test";
RdKafka::Conf *conf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);
conf->set("metadata.broker.list", brokers, errstr);
RdKafka::Producer *producer = RdKafka::Producer::create(conf, errstr);
if (!producer) {
std::cerr << "Failed to create producer: " << errstr << std::endl;
return 1;
}
RdKafka::Topic *rd_topic = RdKafka::Topic::create(producer, topic, tconf, errstr);
RdKafka::ErrorCode resp = producer->produce(rd_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;
}
delete rd_topic;
delete producer;
return 0;
}
這段代碼創建了一個生產者,將消息發送到指定的Kafka主題中。你可以根據需要修改代碼來適配你的場景。同時,你可以通過librdkafka的文檔來了解更多的API和功能。