rust 访问 kafka

kafka

创建client

let brokers = vec!["192.168.1.92:9092".to_owned()];
let topics = vec![
    "tp1".to_string(),
    "tp2".to_string(),
    "tp3".to_string(),
    "tp4".to_string(),
];

let mut client = KafkaClient::new(brokers);

client.load_metadata(&topics).unwrap();

client
	.topics()
	.iter()
	.filter(|tp| !tp.name().starts_with("__"))
	.for_each(|tp| {
	   for partition in tp.partitions() {
	       println!(
	           "{} #{} => {}",
	           tp.name(),
	           partition.id(),
	           partition.leader().map(Broker::host).unwrap_or("no-leader!")
	       );
	   }
	});

client 的 load_metadata 方法:参数是一个vector,load vector 中 topic 的 metadata。当服务端参数 auto.create.topics.enable 为 true 时,会自动创建不存在的 topic。这样的方式是不好的,应该使用 client 的 load_metadata_all 方法,将所有 topic 的 metadata 都先加载,然后在应用程序中做过滤。

let brokers = vec!["192.168.1.92:9092".to_owned()];
let topics = vec!["tp1".to_string(), "tp2".to_string()];

let mut client = KafkaClient::new(brokers);
client.load_metadata_all().unwrap();

client
    .topics()
    .iter()
    .filter(|tp| !tp.name().starts_with("__"))
    .filter(|tp| topics.contains(&tp.name().to_string()))
    .for_each(|tp| {
        for partition in tp.partitions() {
            println!(
                "{} #{} => {}",
                tp.name(),
                partition.id(),
                partition.leader().map(Broker::host).unwrap_or("no-leader!")
            );
        }
    });
  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值