亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

c++中kafka怎么發送json數據

小億
93
2024-05-16 09:39:17
欄目: 編程語言

在C++中使用librdkafka庫可以很方便地發送JSON數據到Kafka。下面是一個簡單的示例代碼:

#include <librdkafka/rdkafkacpp.h>
#include <iostream>
#include <string>

int main() {
    std::string brokers = "localhost:9092";
    std::string topic = "test_topic";

    RdKafka::Conf *conf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);
    RdKafka::Conf *tconf = RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC);

    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 *kafka_topic = RdKafka::Topic::create(producer, topic, tconf, errstr);

    if (!kafka_topic) {
        std::cerr << "Failed to create topic: " << errstr << std::endl;
        return 1;
    }

    std::string json_data = "{\"key\": \"value\"}";

    RdKafka::ErrorCode resp = producer->produce(kafka_topic, RdKafka::Topic::PARTITION_UA, RdKafka::Producer::RK_MSG_COPY,
        const_cast<char *>(json_data.c_str()), json_data.size(), NULL, NULL);

    if (resp != RdKafka::ERR_NO_ERROR) {
        std::cerr << "Failed to produce message: " << RdKafka::err2str(resp) << std::endl;
        return 1;
    }

    producer->flush(1000);

    delete kafka_topic;
    delete producer;

    return 0;
}

在這個示例中,我們首先創建一個生產者和一個主題對象,然后使用produce方法發送一個JSON數據到Kafka主題。在實際使用中,你可能需要根據你的需求調整代碼,并添加錯誤處理邏輯。

0
涟源市| 北川| 平湖市| 铁力市| 紫云| 扎兰屯市| 扎囊县| 宝清县| 永福县| 镇安县| 海兴县| 正蓝旗| 肥城市| 蒙阴县| 丹阳市| 仁布县| 岗巴县| 安龙县| 宣汉县| 云霄县| 双城市| 塔城市| 绿春县| 惠来县| 荆州市| 英超| 资阳市| 尚志市| 柞水县| 随州市| 武清区| 惠水县| 巨鹿县| 阆中市| 磴口县| 林州市| 泾阳县| 甘南县| 松溪县| 璧山县| 简阳市|