安装 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 变量的值。

consumer.cpp 文件的第58~63行修改如下(只修改了59行和61行,为看起来直观一些多粘了几行):

    //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行,为看起来直观一些多粘了几行):

    //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 (控制台交互式的程序,需要开两个窗口)

$ 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


aneutron
6 声望2 粉丝