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!")
);
}
});