c++中kafka的使用方法是什么

803
2024/5/1 9:40:21
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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和功能。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c++随机数的实现方式是什么