Ubuntu下C语言操作kafka示例

目录

安装kafka:

安装librdkafka

consumer

Producer

测试运行


安装kafka:

Ubuntu下Kafka安装及使用_ubuntu安装kafka-CSDN博客

安装librdkafka

github地址:GitHub - confluentinc/librdkafka: The Apache Kafka C/C++ library

$ apt install librdkafka-dev

安装路径如下:

consumer

/*** 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;
}

编译:

gcc consumer.c -o consumer -I/usr/include/librdkafka -L/usr/lib/x86_64-linux-gnu -lrdkafka++ -lrdkafka

Producer

/*** 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;
}

编译:

gcc producer.c -o producer -I/usr/include/librdkafka -L/usr/lib/x86_64-linux-gnu -lrdkafka++ -lrdkafka

测试运行

启动kafka:

bin/kafka-server-start.sh config/server.properties&

创建主题:demo1是主机名,mydemo1是主题。

./bin/kafka-topics.sh --create --bootstrap-server demo1:9092 --replication-factor 1 --partitions 1 --topic mydemo1

启动producer:

./producer demo1:9092 mydemo1

启动consumer:

./consumer demo1:9092 0 mydemo1

在producer终端输入测试消息,在consumer终端能够看到测试消息。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/64665.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

小红书关键词搜索采集 | AI改写 | 无水印下载 | 多维表格 | 采集同步飞书

小红书关键词搜索采集 | AI改写 | 无水印下载 | 多维表格 | 采集同步飞书 一、下载影刀&#xff1a; https://www.winrobot360.com/share/activity?inviteUserUuid595634970300317698 二、加入应用市场 https://www.yingdao.com/share/accede/?inviteKeyb2d3f22a-fd6c-4a…

WatchAlert - 开源多数据源告警引擎

概述 在现代 IT 环境中&#xff0c;监控和告警是确保系统稳定性和可靠性的关键环节。然而&#xff0c;随着业务规模的扩大和数据源的多样化&#xff0c;传统的单一数据源告警系统已经无法满足复杂的需求。为了解决这一问题&#xff0c;我开发了一个开源的多数据源告警引擎——…

单片机:实现HC-SR04超声波测距(附带源码)

使用单片机实现 HC-SR04 超声波测距模块 的功能&#xff0c;通常用于测量物体与超声波传感器之间的距离。HC-SR04 模块通过发射超声波信号并测量其返回时间来计算距离。单片机&#xff08;如 STM32、51 系列、Arduino 等&#xff09;可用来控制该模块的工作&#xff0c;并处理返…

Python langchain ReAct 使用范例

0. 介绍 ReAct: Reasoning Acting &#xff0c;ReAct Prompt 由 few-shot task-solving trajectories 组成&#xff0c;包括人工编写的文本推理过程和动作&#xff0c;以及对动作的环境观察。 1. 范例 langchain version 0.3.7 $ pip show langchain Name: langchain Ver…

selenium工作原理

原文链接&#xff1a;https://blog.csdn.net/weixin_67603503/article/details/143226557 启动浏览器和绑定端口 当你创建一个 WebDriver 实例&#xff08;如 webdriver.Chrome()&#xff09;时&#xff0c;Selenium 会启动一个新的浏览器实例&#xff0c;并为其分配一个特定的…

CTF知识集-SSRF

title: CTF知识集-SSRF 写在开头可能用到的提示 SSRF入口也可以尝试读文件&#xff0c;例如file:///etc/passwd127.0.0.1/localhost可以用127.1 | 127.0.1 来表示&#xff0c;做题的还可能可以用http://0 来访问本地如果过滤ip&#xff0c;可以尝试使用进制转换来绕过&#x…

PDFMathTranslate 一个基于AI优秀的PDF论文翻译工具

PDFMathTranslate 是一个设想中的工具&#xff0c;旨在翻译PDF文档中的数学内容。以下是这个工具的主要特点和使用方法&#xff1a; 链接&#xff1a;https://www.modelscope.cn/studios/AI-ModelScope/PDFMathTranslate 功能特点 数学公式识别&#xff1a;利用先进的OCR&…

ChatGPT生成接口测试用例(二)

5.1.4 自动生成测试数据 测试数据的生成通常是接口测试的一个烦琐任务。ChatGPT可以帮助测试团队生成测试数据&#xff0c;包括各种输入和它们的组合。测试人员可以描述他们需要的数据类型和范围&#xff0c;ChatGPT可以生成符合要求的测试数据&#xff0c;从而减轻测试人员的负…

@pytest.fixture() 跟 @pytest.fixture有区别吗?

在iOS UI 自动化工程里面最早我用的是pytest.fixture()&#xff0c;因为在pycharm中联想出来的fixture是带&#xff08;&#xff09;的&#xff0c;后来偶然一次我没有带&#xff08;&#xff09;发现也没有问题&#xff0c;于是详细查了一下pytest.fixture() 和 pytest.fixtur…

项目管理工具Maven(一)

Maven的概念 什么是Maven 翻译为“专家”&#xff0c;“内行”Maven是跨平台的项目管理工具。主要服务于基于Java平台的项目构建&#xff0c;依赖管理和项目信息管理。什么是理想的项目构建&#xff1f; 高度自动化&#xff0c;跨平台&#xff0c;可重用的组件&#xff0c;标准…

webstorm中vue项目import的内容不能直接ctrl+鼠标点击跳转(若依等vue项目)

webstorm中vue项目import的内容不能直接ctrl鼠标点击跳转&#xff08;若依等vue项目&#xff09; https://blog.csdn.net/wangzhenhuait/article/details/121231087 https://blog.csdn.net/qq_26711723/article/details/137586701?spm1001.2101.3001.6650.5&utm_mediumd…

深入解析MySQL Explain关键字:字段意义及调优策略

一、引言 在数据库优化过程中&#xff0c;Explain关键字发挥着至关重要的作用。它可以帮助我们了解MySQL如何执行SQL语句&#xff0c;从而找出潜在的性能瓶颈。下面我们将从Explain表的各个字段入手&#xff0c;逐一解释其意义&#xff0c;并探讨如何利用Explain进行调优。 二…

C++设计模式:组合模式(公司架构案例)

组合模式是一种非常有用的设计模式&#xff0c;用于解决**“部分-整体”**问题。它允许我们用树形结构来表示对象的层次结构&#xff0c;并且让客户端可以统一地操作单个对象和组合对象。 组合模式的核心思想 什么是组合模式&#xff1f; 组合模式的目的是将对象组织成树形结…

ElasticSearch 自动补全

1、前言 当用户在搜索框输入字符时&#xff0c;我们应该提示出与该字符有关的搜索项&#xff0c;根据用户输入的字母&#xff0c;提示完整词条的功能&#xff0c;就是自动补全。 2、安装拼音分词器 Github地址&#xff1a;https://github.com/infinilabs/analysis-pinyin 插件…

UML 建模实验

文章目录 实验一 用例图一、安装并熟悉软件EnterpriseArchitect16二、用例图建模 实验二 类图、包图、对象图类图第一题第二题 包图对象图第一题第二题 实验三 顺序图、通信图顺序图银行系统学生指纹考勤系统饮料自动销售系统“买到饮料”“饮料已售完”“无法找零”完整版 通信…

Linux环境下 搭建ELk项目 -单机版练习

前言 ELK 项目是一个由三个开源工具组成的日志处理和分析解决方案&#xff0c;ELK 是 Elasticsearch、Logstash 和 Kibana 的首字母缩写。这个项目的目标是帮助用户采集、存储、搜索和可视化大量的日志和事件数据&#xff0c;尤其是在分布式系统中。下面是每个组件的概述&…

探索 Vue.js 组件开发:从基础到进阶的完整指南

引言 在现代前端开发中&#xff0c;Vue.js 凭借其易用性和强大的功能&#xff0c;成为了开发者钟爱的框架之一。其核心理念——组件化开发&#xff0c;不仅让代码更加模块化、可维护&#xff0c;还大大提高了开发效率。本文将从基础入手&#xff0c;详细探讨 Vue.js 组件开发的…

智能工厂的设计软件 三种处理单元(NPU/GPU/CPU)及其在深度学习框架中的作用 之3(百度文库答问 之1)

Q&A&#xff08;百度文库&#xff09; Q1、今天聊聊“智能工厂的设计软件”中的三种处理单元&#xff08;NPU/GPU/CPU&#xff09;。一般来说提起这三者就不得不说“深度学习”。那我们就从这里开始。 请先给出一个程序例子来说明NPU 如何协作CPU和GPU来完成深度学习任务 …

jdk 离线安装脚本

jdk 离线安装脚本 说明脚本使用完整脚本脚本内容说明1、是否卸载原有jdk&#xff0c;检查安装包是否正确2、先卸载、再安装并检验安装成果 说明 经常装服务器环境&#xff0c;根据以前的安装经验写了个安装脚本。本人不是专业运维&#xff0c;也是边百度边写的&#xff0c;发现…

HTTP 常见的请求头有哪些? 作用?常见的使用场景都有哪些?

在 HTTP 协议中,**请求头(Request Headers)**是客户端向服务器发送请求时附带的元数据,主要用于传递请求的相关信息,比如客户端信息、请求的格式要求、认证信息等。理解这些请求头的作用和使用场景对于开发现代 Web 应用至关重要。以下是一些常见的 HTTP 请求头及其作用和…