librdkafka 安裝與使用


title: librdkafka 安裝與使用
copyright: true
date: 2019-05-20 08:53:02
categories: 消息隊列
tags:c++

  • kafka
  • 消息隊列
  • librdkafka
  • MQ

安裝 librdkafka

git clone https://github.com/edenhill/librdkafka.git ./librdkafka
cd ./librdkafka
./configure
# Or, to automatically install dependencies using the system's package manager:
# ./configure --install-deps
# Or, build dependencies from source:
# ./configure --install-deps --source-deps-only
make
sudo make install

使用 librdkafka

librdkafka 中自帶 examples,cpp 目錄下是 C++ 版本的包括兩個 cpp 文件:consumer.cpp 和 producer.cpp,即生產者和消費者。修改其中 brokers 變量和 topic_str 變量的值。git

consumer.cpp 文件的第58~63行修改以下(只修改了59行和61行,爲看起來直觀一些多粘了幾行):github

//broker 列表,能夠用逗號隔開,只寫其中一個也能夠,這是線下測試環境
    std::string brokers = "10.159.1.40:19092,10.159.1.41:19092,10.159.1.42:19092";
    std::string errstr;
    std::string topic_str="test_mq";
    std::vector<std::string> topics;
    topics.push_back(topic_str);

producer.cpp 文件的第31~34行修改以下(只修改了32行和34行,爲看起來直觀一些多粘了幾行):shell

//broker 列表,能夠用逗號隔開,只寫其中一個也能夠,這是線下測試環境
    std::string brokers = "10.159.1.40:19092,10.159.1.41:19092,10.159.1.42:19092";
    std::string errstr;
    std::string topic_str="test_mq";

編譯 consumer.cpp 和 producer.cpp測試

$ cd ~/librdkafka/examples/cpp
$ g++ -o consumer consumer.cpp -lrdkafka++ -lrdkafka -lstdc++ -lbaas_c_style_interface -I~/librdkafka/include -L~/librdkafka/lib

$ g++ -o producer producer.cpp -lrdkafka++ -lrdkafka -lstdc++ -lbaas_c_style_interface -I~/librdkafka/include -L~/librdkafka/lib

運行 producer 和 consumer (控制檯交互式的程序,須要開兩個窗口)ui

$ cd ~/librdkafka/examples/cpp

$ ./producer
% Created producer rdkafka#producer-1
hello world
% Produced message (11 bytes)

$ ./consumer
% Created consumer rdkafka#consumer-1
Read msg at offset 7
hello world

qcode.png

相關文章
相關標籤/搜索