Rust消费kafka

rust 复制代码
use futures::stream::StreamExt; // 引入 StreamExt 以使用 next() 方法
use rdkafka::config::ClientConfig;
use rdkafka::consumer::{CommitMode, Consumer, StreamConsumer};
use rdkafka::error::KafkaResult;
use rdkafka::message::{Message};

async fn run_consumer() -> KafkaResult<()> {
    let consumer: StreamConsumer = ClientConfig::new()
        .set("group.id", "test_group")
        .set("bootstrap.servers", "localhost:9092")
        .set("enable.auto.commit", "true")
        .set("session.timeout.ms", "6000")
        .set("auto.offset.reset", "earliest")
        .create()
        .expect("Consumer creation failed");

    consumer.subscribe(&["test_topic"]).expect("Can't subscribe to specified topics");

    let mut message_stream = consumer.stream();

    while let Some(message) = message_stream.next().await {
        match message {
            Ok(m) => {
                match m.payload_view::<str>() {
                    Some(Ok(payload)) => {
                        println!("Key: '{:?}', Payload: '{}'", m.key(), payload);
                    }
                    Some(Err(e)) => {
                        eprintln!("Error while deserializing message payload: {:?}", e);
                    }
                    None => {
                        println!("Key: '{:?}', Payload: <empty>", m.key());
                    }
                }
                consumer.commit_message(&m, CommitMode::Async)?;
            }
            Err(e) => eprintln!("Kafka error: {}", e),
        }
    }
    Ok(())
}

fn main() {
    let runtime = tokio::runtime::Runtime::new().unwrap();
    runtime.block_on(run_consumer()).unwrap();
}

dependencies

rdkafka = "0.36.2"

tokio = { version = "1.36.0", features = ["full"] }

futures = "0.3.30"

target.x86_64-unknown-linux-musl

linker = "x86_64-linux-musl-gcc"

相关推荐
小白学大数据25 分钟前
现代Python爬虫开发范式:基于Asyncio的高可用架构实战
开发语言·爬虫·python·架构
渔舟小调35 分钟前
P19 | 前端加密通信层 pikachuNetwork.js 完整实现
开发语言·前端·javascript
不爱吃炸鸡柳37 分钟前
数据结构精讲:树 → 二叉树 → 堆 从入门到实战
开发语言·数据结构
网络安全许木37 分钟前
自学渗透测试第21天(基础命令复盘与DVWA熟悉)
开发语言·网络安全·渗透测试·php
t***54442 分钟前
如何在Dev-C++中使用Clang编译器
开发语言·c++
码界筑梦坊1 小时前
93-基于Python的中药药材数据可视化分析系统
开发语言·python·信息可视化
Cosmoshhhyyy2 小时前
《Effective Java》解读第49条:检查参数的有效性
java·开发语言
棋子入局2 小时前
C语言制作消消乐游戏(2)
c语言·开发语言·游戏
布谷歌2 小时前
常见的OOM错误 ( OutOfMemoryError全类型详解)
java·开发语言
WangJunXiang62 小时前
GFS分布式文件系统
开发语言·php