使用C語言操作kafka ---- librdkafka

1 安裝librdkafka

git clone https://github.com/edenhill/librdkafka.git
cd librdkafka
git checkout v1.7.0
./configure
make
sudo make install
sudo ldconfig
?

?在librdkafka的examples目錄下會有示例程序。比如consumer的啟動需要下列參數

./consumer <broker> <group.id> <topic1> <topic2>..

?指定broker、group id、topic(可以訂閱多個)。示例:

指定broker、group id、topic(可以訂閱多個)。示例:

縮略語介紹:

?

2 開啟kafka相關服務

2.1 啟動zookeeper

啟動zookeeper可以通過下面的腳本來啟動zookeeper服務,當然,也可以自己獨立搭建zookeeper的集群來實現。這里我們直接使用kafka自帶的zookeeper。

?

cd bin/
# 前臺運行:
sh zookeeper-server-start.sh  ../config/zookeeper.properties# 后臺運行:
sh zookeeper-server-start.sh -daemon ../config/zookeeper.properties

?可以通過命令lsof -i:2181 查看zookeeper是否啟動成功。

$ lsof -i:2181
COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
java    74930  fly   96u  IPv6 734467      0t0  TCP *:2181 (LISTEN)

2.2 啟動Kafka

啟動kafka(kafka安裝路徑的bin目錄下執行),默認啟動端口9092。

sh kafka-server-start.sh -daemon ../config/server.properties

2.3 創建topic

sh kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic test

參數說明:

–create 是創建主題的的動作指令。
–zookeeper 指定kafka所連接的zookeeper服務地址。
–replicator-factor 指定了副本因子(即副本數量); 表示該topic需要在不同的broker中保存幾份,這里設置成1,表示在兩個broker中保存兩份Partitions分區數。
–partitions 指定分區個數;多通道,類似車道。
–topic 指定所要創建主題的名稱,比如test。
?

3 c語言操作kafka的范例

3.1 消費者

在librdkafka\examples下有consumer.c文件,該文件是一個c語言操作kafka的代碼范例,內容如下。

/*** Simple high-level balanced Apache Kafka consumer* using the Kafka driver from librdkafka* (https://github.com/edenhill/librdkafka)*/#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <ctype.h>/* Typical include path would be <librdkafka/rdkafka.h>, but this program* is builtin from within the librdkafka source tree and thus differs. */
//#include <librdkafka/rdkafka.h>
#include "rdkafka.h"static volatile sig_atomic_t run = 1;/*** @brief Signal termination of program*/
static void stop (int sig) {run = 0;
}/*** @returns 1 if all bytes are printable, else 0.*/
static int is_printable (const char *buf, size_t size) {size_t i;for (i = 0 ; i < size ; i++)if (!isprint((int)buf[i]))return 0;return 1;
}int main (int argc, char **argv) {rd_kafka_t *rk;          /* Consumer instance handle */rd_kafka_conf_t *conf;   /* Temporary configuration object */rd_kafka_resp_err_t err; /* librdkafka API error code */char errstr[512];        /* librdkafka API error reporting buffer */const char *brokers;     /* Argument: broker list */const char *groupid;     /* Argument: Consumer group id */char **topics;           /* Argument: list of topics to subscribe to */int topic_cnt;           /* Number of topics to subscribe to */rd_kafka_topic_partition_list_t *subscription; /* Subscribed topics */int i;/** Argument validation*/if (argc < 4) {fprintf(stderr,"%% Usage: ""%s <broker> <group.id> <topic1> <topic2>..\n",argv[0]);return 1;}brokers   = argv[1];groupid   = argv[2];topics    = &argv[3];topic_cnt = argc - 3;/** Create Kafka client configuration place-holder*/conf = rd_kafka_conf_new();	// 創建配置文件/* Set bootstrap broker(s) as a comma-separated list of* host or host:port (default port 9092).* librdkafka will use the bootstrap brokers to acquire the full* set of brokers from the cluster. */if (rd_kafka_conf_set(conf, "bootstrap.servers", brokers,errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) {fprintf(stderr, "%s\n", errstr);rd_kafka_conf_destroy(conf);return 1;}/* Set the consumer group id.* All consumers sharing the same group id will join the same* group, and the subscribed topic' partitions will be assigned* according to the partition.assignment.strategy* (consumer config property) to the consumers in the group. */if (rd_kafka_conf_set(conf, "group.id", groupid,errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) {fprintf(stderr, "%s\n", errstr);rd_kafka_conf_destroy(conf);return 1;}/* If there is no previously committed offset for a partition* the auto.offset.reset strategy will be used to decide where* in the partition to start fetching messages.* By setting this to earliest the consumer will read all messages* in the partition if there was no previously committed offset. */if (rd_kafka_conf_set(conf, "auto.offset.reset", "earliest",errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) {fprintf(stderr, "%s\n", errstr);rd_kafka_conf_destroy(conf);return 1;}/** Create consumer instance.** NOTE: rd_kafka_new() takes ownership of the conf object*       and the application must not reference it again after*       this call.*/// 創建一個kafka消費者rk = rd_kafka_new(RD_KAFKA_CONSUMER, conf, errstr, sizeof(errstr));if (!rk) {fprintf(stderr,"%% Failed to create new consumer: %s\n", errstr);return 1;}conf = NULL; /* Configuration object is now owned, and freed,* by the rd_kafka_t instance. *//* Redirect all messages from per-partition queues to* the main queue so that messages can be consumed with one* call from all assigned partitions.** The alternative is to poll the main queue (for events)* and each partition queue separately, which requires setting* up a rebalance callback and keeping track of the assignment:* but that is more complex and typically not recommended. */rd_kafka_poll_set_consumer(rk);// poll機制,設置消費者實例到poll中/* Convert the list of topics to a format suitable for librdkafka */// 創建主題分區列表subscription = rd_kafka_topic_partition_list_new(topic_cnt);for (i = 0 ; i < topic_cnt ; i++)rd_kafka_topic_partition_list_add(subscription,topics[i],/* the partition is ignored* by subscribe() */RD_KAFKA_PARTITION_UA);/* Subscribe to the list of topics */err = rd_kafka_subscribe(rk, subscription);if (err) {fprintf(stderr,"%% Failed to subscribe to %d topics: %s\n",subscription->cnt, rd_kafka_err2str(err));rd_kafka_topic_partition_list_destroy(subscription);rd_kafka_destroy(rk);return 1;}fprintf(stderr,"%% Subscribed to %d topic(s), ""waiting for rebalance and messages...\n",subscription->cnt);rd_kafka_topic_partition_list_destroy(subscription);/* Signal handler for clean shutdown */signal(SIGINT, stop);/* Subscribing to topics will trigger a group rebalance* which may take some time to finish, but there is no need* for the application to handle this idle period in a special way* since a rebalance may happen at any time.* Start polling for messages. */while (run) {rd_kafka_message_t *rkm;rkm = rd_kafka_consumer_poll(rk, 100);if (!rkm)continue; /* Timeout: no message within 100ms,*  try again. This short timeout allows*  checking for `run` at frequent intervals.*//* consumer_poll() will return either a proper message* or a consumer error (rkm->err is set). */if (rkm->err) {/* Consumer errors are generally to be considered* informational as the consumer will automatically* try to recover from all types of errors. */fprintf(stderr,"%% Consumer error: %s\n",rd_kafka_message_errstr(rkm));rd_kafka_message_destroy(rkm);continue;}/* Proper message. */printf("Message on %s [%"PRId32"] at offset %"PRId64":\n",rd_kafka_topic_name(rkm->rkt), rkm->partition,rkm->offset);/* Print the message key. */if (rkm->key && is_printable(rkm->key, rkm->key_len))printf(" Key: %.*s\n",(int)rkm->key_len, (const char *)rkm->key);else if (rkm->key)printf(" Key: (%d bytes)\n", (int)rkm->key_len);/* Print the message value/payload. */if (rkm->payload && is_printable(rkm->payload, rkm->len))printf(" Value: %.*s\n",(int)rkm->len, (const char *)rkm->payload);else if (rkm->payload)printf(" Value: (%d bytes)\n", (int)rkm->len);rd_kafka_message_destroy(rkm);}/* Close the consumer: commit final offsets and leave the group. */fprintf(stderr, "%% Closing consumer\n");rd_kafka_consumer_close(rk);/* Destroy the consumer */rd_kafka_destroy(rk);return 0;
}

3.2 生產者

在librdkafka\examples下有producer.c文件,該文件是一個c語言操作kafka的代碼范例,內容如下。

/*** Simple Apache Kafka producer* using the Kafka driver from librdkafka* (https://github.com/edenhill/librdkafka)*/#include <stdio.h>
#include <signal.h>
#include <string.h>/* Typical include path would be <librdkafka/rdkafka.h>, but this program* is builtin from within the librdkafka source tree and thus differs. */
#include "rdkafka.h"static volatile sig_atomic_t run = 1;/*** @brief Signal termination of program*/
static void stop (int sig) {run = 0;fclose(stdin); /* abort fgets() */
}/*** @brief Message delivery report callback.** This callback is called exactly once per message, indicating if* the message was succesfully delivered* (rkmessage->err == RD_KAFKA_RESP_ERR_NO_ERROR) or permanently* failed delivery (rkmessage->err != RD_KAFKA_RESP_ERR_NO_ERROR).** The callback is triggered from rd_kafka_poll() and executes on* the application's thread.*/
static void dr_msg_cb (rd_kafka_t *rk,const rd_kafka_message_t *rkmessage, void *opaque) {if (rkmessage->err)fprintf(stderr, "%% Message delivery failed: %s\n",rd_kafka_err2str(rkmessage->err));elsefprintf(stderr,"%% Message delivered (%zd bytes, ""partition %"PRId32")\n",rkmessage->len, rkmessage->partition);/* The rkmessage is destroyed automatically by librdkafka */
}int main (int argc, char **argv) {rd_kafka_t *rk;         /* Producer instance handle */rd_kafka_conf_t *conf;  /* Temporary configuration object */char errstr[512];       /* librdkafka API error reporting buffer */char buf[512];          /* Message value temporary buffer */const char *brokers;    /* Argument: broker list */const char *topic;      /* Argument: topic to produce to *//** Argument validation*/if (argc != 3) {fprintf(stderr, "%% Usage: %s <broker> <topic>\n", argv[0]);return 1;}brokers = argv[1];topic   = argv[2];/** Create Kafka client configuration place-holder*/conf = rd_kafka_conf_new();/* Set bootstrap broker(s) as a comma-separated list of* host or host:port (default port 9092).* librdkafka will use the bootstrap brokers to acquire the full* set of brokers from the cluster. */if (rd_kafka_conf_set(conf, "bootstrap.servers", brokers,errstr, sizeof(errstr)) != RD_KAFKA_CONF_OK) {fprintf(stderr, "%s\n", errstr);return 1;}/* Set the delivery report callback.* This callback will be called once per message to inform* the application if delivery succeeded or failed.* See dr_msg_cb() above.* The callback is only triggered from rd_kafka_poll() and* rd_kafka_flush(). */rd_kafka_conf_set_dr_msg_cb(conf, dr_msg_cb);/** Create producer instance.** NOTE: rd_kafka_new() takes ownership of the conf object*       and the application must not reference it again after*       this call.*/rk = rd_kafka_new(RD_KAFKA_PRODUCER, conf, errstr, sizeof(errstr));if (!rk) {fprintf(stderr,"%% Failed to create new producer: %s\n", errstr);return 1;}/* Signal handler for clean shutdown */signal(SIGINT, stop);fprintf(stderr,"%% Type some text and hit enter to produce message\n""%% Or just hit enter to only serve delivery reports\n""%% Press Ctrl-C or Ctrl-D to exit\n");while (run && fgets(buf, sizeof(buf), stdin)) {size_t len = strlen(buf);rd_kafka_resp_err_t err;if (buf[len-1] == '\n') /* Remove newline */buf[--len] = '\0';if (len == 0) {/* Empty line: only serve delivery reports */rd_kafka_poll(rk, 0/*non-blocking */);continue;}/** Send/Produce message.* This is an asynchronous call, on success it will only* enqueue the message on the internal producer queue.* The actual delivery attempts to the broker are handled* by background threads.* The previously registered delivery report callback* (dr_msg_cb) is used to signal back to the application* when the message has been delivered (or failed).*/retry:err = rd_kafka_producev(/* Producer handle */rk,/* Topic name */RD_KAFKA_V_TOPIC(topic),/* Make a copy of the payload. */RD_KAFKA_V_MSGFLAGS(RD_KAFKA_MSG_F_COPY),/* Message value and length */RD_KAFKA_V_VALUE(buf, len),/* Per-Message opaque, provided in* delivery report callback as* msg_opaque. */RD_KAFKA_V_OPAQUE(NULL),/* End sentinel */RD_KAFKA_V_END);if (err) {/** Failed to *enqueue* message for producing.*/fprintf(stderr,"%% Failed to produce to topic %s: %s\n",topic, rd_kafka_err2str(err));if (err == RD_KAFKA_RESP_ERR__QUEUE_FULL) {/* If the internal queue is full, wait for* messages to be delivered and then retry.* The internal queue represents both* messages to be sent and messages that have* been sent or failed, awaiting their* delivery report callback to be called.** The internal queue is limited by the* configuration property* queue.buffering.max.messages */rd_kafka_poll(rk, 1000/*block for max 1000ms*/);goto retry;}} else {fprintf(stderr, "%% Enqueued message (%zd bytes) ""for topic %s\n",len, topic);}/* A producer application should continually serve* the delivery report queue by calling rd_kafka_poll()* at frequent intervals.* Either put the poll call in your main loop, or in a* dedicated thread, or call it after every* rd_kafka_produce() call.* Just make sure that rd_kafka_poll() is still called* during periods where you are not producing any messages* to make sure previously produced messages have their* delivery report callback served (and any other callbacks* you register). */rd_kafka_poll(rk, 0/*non-blocking*/);}/* Wait for final messages to be delivered or fail.* rd_kafka_flush() is an abstraction over rd_kafka_poll() which* waits for all messages to be delivered. */fprintf(stderr, "%% Flushing final messages..\n");rd_kafka_flush(rk, 10*1000 /* wait for max 10 seconds */);/* If the output queue is still not empty there is an issue* with producing messages to the clusters. */if (rd_kafka_outq_len(rk) > 0)fprintf(stderr, "%% %d message(s) were not delivered\n",rd_kafka_outq_len(rk));/* Destroy the producer instance */rd_kafka_destroy(rk);return 0;
}

?

3.3 生產者和消費者的交互


(1)啟動消費者。

./consumer localhost:9092 0 test
1
顯示:

% Subscribed to 1 topic(s), waiting for rebalance and messages...
1
(2)啟動生產者。

./producer localhost:9092 test

總結

  1. 一個分區只能被一個消費者讀取。如果一個topic只有一個分區,多個消費者讀取時只有一個消費者能讀到數據;單個分區開啟多個消費者去讀取數據是沒有意義的。

?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:
http://www.pswp.cn/news/210098.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/210098.shtml
英文地址,請注明出處:http://en.pswp.cn/news/210098.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

一對一聊天程序

package untitled1.src;import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.net.*;public class MyServer extends JFrame{private ServerSocket server; // 服務器套接字pri…

【漏洞復現】華脈智聯指揮調度平臺/xml_edit/fileread.php文件讀取漏洞

Nx01 產品簡介 深圳市華脈智聯科技有限公司&#xff0c;融合通信系統將公網集群系統、專網寬帶集群系統、不同制式、不同頻段的短波/超短波對講、模擬/數字集群系統、辦公電話系統、廣播系統、集群單兵視頻、視頻監控系統、視頻會議系統等融為一體&#xff0c;集成了專業的有線…

第一課【習題】HarmonyOS應用/元服務上架

元服務發布的國家與地區僅限于“中國大陸” 編譯打包的軟件包存放在項目目錄build > outputs > default下 創建應用時&#xff0c;應用包名需要和app.json5或者config.json文件中哪個字段保持一致&#xff1f; 發布應用時需要創建證書&#xff0c;證書類型選擇什么…

web前端實現LED功能、液晶顯示時間、數字

MENU 效果演示html部分JavaScript部分css部分 效果演示 html部分 <div id"app"><!-- 頁面 --><div class"time-box"><!-- 時 --><div class"house-box"><bit-component :num"houseTem"></bit…

編譯器緩存

2023年12月6日&#xff0c;周三晚上 使用編譯器緩存有什么用 編譯器緩存是一種用于加速編譯過程的工具&#xff0c;它可以緩存已編譯的對象文件和依賴關系&#xff0c;以便在后續構建中重復使用。使用編譯器緩存可以帶來以下幾個好處&#xff1a; 加快編譯速度&#xff1a;編譯…

TS型變與對象類型進階

子類型&#xff1a;給定兩個類型A和B&#xff0c;假設B是A的子類型&#xff0c;那么在需要A的地方都可以放心使用B。計作 A <: B &#xff08;A是B的子類型&#xff09;。 超類型正好與子類型相反。A >: B &#xff08;A是B的超類型&#xff09;。 1 TS 類型 可賦值性…

使用cmake構建Qt6.6的qt quick項目,添加應用程序圖標的方法

最近&#xff0c;在學習qt的過程中&#xff0c;遇到了一個難題&#xff0c;不知道如何給應用程序添加圖標&#xff0c;按照網上的方法也沒有成功&#xff0c;后來終于自己摸索出了一個方法。 1、準備一張圖片作為圖標&#xff0c;保存到工程目錄下面&#xff0c;如logo.ico。 …

Qt 編譯fcitx-qt5 插件支持中文輸入法

前言 在Linux系統上會遇到Qt開發的程序無法輸入中文的情況&#xff0c;原因就是因為輸入法框架是采用的fcitx&#xff0c;而不是ibus&#xff0c;Qt默認只支持ibus輸入法框架。在Qt/5.15.2/gcc_64/plugins/platforminputcontexts/路徑下可以看到&#xff0c;只有libibusplatfo…

引入JavaScript文件的5種方式

在HTML文件中&#xff0c;可以使用以下5種方式引入JavaScript文件&#xff1a; 1.內聯方式&#xff08;Inline&#xff09;&#xff1a; 在HTML的<script>標簽中直接編寫JavaScript代碼。 示例&#xff1a; <script>// JavaScript代碼 </script>2.外部文件…

Python Selenium3 簡單操作進行百度搜索

當前環境&#xff1a;Win10 Python3.7 selenium3.141.0&#xff0c;urllib31.26.2 from selenium import webdriver import timeif __name__ __main__:# Chrome 路徑CHROME_PATH rC:\Program Files (x86)\65.0.3312.0\chrome-win32\chrome.exe# ChromeDriver 路徑CHROMEDR…

mybatis的快速入門以及spring boot整合mybatis(二)

需要用到的SQL腳本&#xff1a; CREATE TABLE dept (id int unsigned PRIMARY KEY AUTO_INCREMENT COMMENT ID, 主鍵,name varchar(10) NOT NULL UNIQUE COMMENT 部門名稱,create_time datetime DEFAULT NULL COMMENT 創建時間,update_time datetime DEFAULT NULL COMMENT 修改…

極智芯 | 解讀國產AI算力 靈汐產品矩陣

歡迎關注我的公眾號 [極智視界],獲取我的更多經驗分享 大家好,我是極智視界,本文分享一下 解讀國產AI算力 靈汐產品矩陣。 邀您加入我的知識星球「極智視界」,星球內有超多好玩的項目實戰源碼和資源下載,鏈接:https://t.zsxq.com/0aiNxERDq [系列聲明:最近寫了十余篇 &…

低多邊形建筑3D模型紋理貼圖

在線工具推薦&#xff1a; 3D數字孿生場景編輯器 - GLTF/GLB材質紋理編輯器 - 3D模型在線轉換 - Three.js AI自動紋理開發包 - YOLO 虛幻合成數據生成器 - 三維模型預覽圖生成器 - 3D模型語義搜索引擎 當談到游戲角色的3D模型風格時&#xff0c;有幾種不同的風格&#xf…

基于SSM的鞍山職業技術學院圖書借閱管理系統

文章目錄 項目介紹主要功能截圖:部分代碼展示設計總結項目獲取方式?? 作者主頁:超級無敵暴龍戰士塔塔開 ?? 簡介:Java領域優質創作者??、 簡歷模板、學習資料、面試題庫【關注我,都給你】 ??文末獲取源碼聯系?? 項目介紹 基于SSM的鞍山職業技術學院圖書借閱管理…

樹莓派CSI攝像頭在新系統(23年12月)中的不用設置了,沒有開關,也沒有raspistill

網上都是老信息&#xff0c;用的raspistill命令&#xff0c;至少新系統沒有這個東西了&#xff0c;也不會在sudo raspi-config里面也沒有攝像頭的開關了。 ls /dev/video* 能看到攝像頭video0&#xff0c;但是vcgencmd get_camera supported0&#xff0c; detected0&#xff0…

【python】閉包和裝飾器

前置知識&#xff1a; 函數的本質就是變量名可以把函數作為參數傳遞&#xff0c;例如&#xff1a; def func():print("我是func")# 接收的fn是個函數 def handle(fn): # 調用函數fn()handle(func)可以把函數作為返回值返回&#xff0c;例如 def func():def func2(…

CPU的三大調度

計算機系統中的調度可以分為不同層次&#xff0c;包括作業調度、內存調度和進程調度。這三種調度分別負責管理和優化計算機系統中不同層次的資源分配和執行順序。 高級調度&#xff1a;作業調度&#xff08;Job Scheduling&#xff09;&#xff1a; 作業調度是指對提交到計算…

了解c++11中的新增

一&#xff0c;統一的初始化列表 在引入c11后&#xff0c;我們得出計劃都可以用初始化列表進行初始化。 C11 擴大了用大括號括起的列表 ( 初始化列表 ) 的使用范圍&#xff0c;使其可用于所有的內置類型和用戶自 定義的類型&#xff0c; 使用初始化列表時&#xff0c;可添加等…

Vue學習計劃-Vue2--VueCLi(二)vuecli腳手架創建的項目內部主要文件分析

1. 文件分析 1. 補充&#xff1a; 什么叫單文件組件&#xff1f; 一個文件中只有一個組件 vue-cli創建的項目中&#xff0c;.vue的文件都是單文件組件&#xff0c;例如App.vue 2. 進入分析 1. package.json: 項目依賴配置文件&#xff1a; 如圖&#xff0c;我們說主要的屬性…

性能測試經典面試題(帶答案)!

概述一下性能測試流程&#xff1f; 1.分析性能需求。挑選用戶使用最頻繁的場景來測試。確定性能指標&#xff0c;比如&#xff1a;事務通過率 為100%&#xff0c;TOP99%是5秒&#xff0c;最大并發用戶為1000人&#xff0c;CPU和內存的使用率在70%以下2.制定性能測試計劃&…