title: librdkafka 安装与使用
copyright: true
date: 2019-05-20 08:53:02
categories: 消息队列
tags:c++
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 中自带 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