1.C++編程中使用librdkafka庫去鏈接kafka集羣分爲生產端,消費端兩個部分。本次是在https://github.com/edenhill/librdkafka 下載源碼編譯,安裝的。過程很簡單再也不這裏詳細說明。git
一.生產端使用github
在編譯完以後會有一個rdkafka_example.cpp,參考他進行編寫程序。主要邏輯以下:編程
RdKafka::Conf *m_conf;
RdKafka::Conf *m_tconf;
RdKafka::Producer *m_producer;
RdKafka::Topic *m_topic;
MyHashPartitionerCb hash_partitioner;
ExampleDeliveryReportCb ex_dr_cb;
ExampleEventCb ex_event_cb;多線程
m_conf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);
m_tconf = RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC);負載均衡
m_tconf->set("partitioner_cb", &hash_partitioner, errstr)線程
m_conf->set("metadata.broker.list", m_sBrokenList, errstr);blog
m_conf->set("queue.buffering.max.ms", "10", errstr); //批量提交隊列
m_conf->set("queue.buffering.max.messages", sMaxMsgs, errstr); get
m_conf->set("event_cb", &ex_event_cb, errstr);kafka
m_conf->set("dr_cb", &ex_dr_cb, errstr);
m_producer = RdKafka::Producer::create(m_conf, errstr);
m_topic = RdKafka::Topic::create(m_producer, m_topicName,m_tconf, errstr);
RdKafka::ErrorCode resp = m_producer->produce(m_topic, m_PartionCn , RdKafka::Producer::RK_MSG_COPY, pData, iDataLen, (const void *)pKey, strlen(pKey),NULL);
m_producer->poll(1);//能夠是poll 0
注意點:
1.成產過程當中的pKey值須要注意一點,不能所有同樣,這會影響到各分區的負載均衡。
2.queue.buffering.max.messages" //本地隊列緩衝值,應該是在10w-50w之間,過小則會處理不過來引發丟棄。
3.在此基礎上加上多線程就知足需求
二.消費端的使用
1.主要參考rdkafka_consumer_example.cpp 文件。
主要邏輯以下:
RdKafka::Conf *m_conf;
RdKafka::Conf *m_tconf;
m_conf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL);
m_tconf = RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC);
ExampleRebalanceCb ex_rebalance_cb;
m_conf->set("rebalance_cb", &ex_rebalance_cb, errstr);
m_conf->set("enable.partition.eof", "true", errstr);
m_conf->set("metadata.broker.list", m_sBrokenList, errstr) //設置服務列表
m_conf->set("auto.commit.interval.ms", g_conf.sCommitTimeVal, errstr)
m_conf->set("group.id", m_sGroupID, errstr)
MyConsumeCb ex_consume_cb;
m_conf->set("consume_cb", &ex_consume_cb, errstr);
ExampleEventCb ex_event_cb;
m_conf->set("event_cb", &ex_event_cb, errstr);
m_tconf->set("auto.offset.reset", "latest", errstr);
m_conf->set("default_topic_conf", m_tconf, errstr);
RdKafka::KafkaConsumer *consumer = RdKafka::KafkaConsumer::create(m_conf, errstr);
std::vector<std::string> topicsVec;
topicsVec.clear();
topicsVec.push_back(m_sTopicName);
RdKafka::ErrorCode err = consumer->subscribe(topicsVec);
while (m_runFlag)
{
RdKafka::Message *msg = consumer->consume(1000);//1000是超時時間單位毫秒
msg_consume(msg, NULL);
delete msg;
}
consumer->close();
delete consumer;
注意點:
1.消費者組中消費者數量不能大於分區數量。不一樣的消費者組能夠消費相同topic
2.加上多線程便可知足多個消費者同時消費。
附上kafka參數的對照表