阅读量:0
在C++中使用Kafka可以通过librdkafka库实现。下面是一个简单的示例代码:
#include #include 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和功能。