String bootstrapServers = "192.163.0.1:9092"; KafkaAdmin kafkaAdmin; AdminClient adminClient; /** * 项目启动调用或者通过@Bean注入 */ public void createKafkaAdmin(){ Map<String, Object> props = new HashMap<>(); props.put("bootstrap.servers", bootstrapServers); props.put("client.id","admin-001"); kafkaAdmin = new KafkaAdmin(props); kafkaAdmin.setAutoCreate(true); adminClient = AdminClient.create(kafkaAdmin.getConfigurationProperties()); } /** * 获取kafka中所有的topic名称 * @return */ public List<String> getAllTopic(){ ListTopicsResult topicList = adminClient.listTopics(); KafkaFuture<Set<String>> kafkaFuture = topicList.names(); Set<String> topicSet = kafkaFuture.get(); topicSet.stream().forEach(e->{ System.err.println("kafka:【"+bootstrapServers+"】存在topic:【"+e"】"); }); return CollectionUtil.newArrayList(topicSet.iterator()); } /** * 创建topic */ public void createTopic(String topicName){ try { //9 -> 分区数量 3->节点数量 NewTopic newTopic = new NewTopic(topicName,9,(short)3); List<NewTopic> newTopics = new ArrayList<>(); newTopics.add(newTopic); CreateTopicsResult createResult = adminClient.createTopics(newTopics); createResult.all().get(); System.err.println("kafka创建topic:【"+topicName+"】成功"); } catch (Exception e) { System.err.println("kafka创建topic:【"+topicName+"】失败"); e.printStackTrace(); } }
标签:adminClient,队列,代码,kafka,topic,kafkaAdmin,props,new From: https://www.cnblogs.com/Sora-L/p/16755295.html