Home  >  Article  >  Java  >  Quick way to create a Kafka topic

Quick way to create a Kafka topic

WBOY
WBOYOriginal
2024-02-01 08:50:06711browse

Quick way to create a Kafka topic

Steps to quickly create a Kafka topic

  1. Import dependencies
<dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka-clients</artifactId>
    <version>3.1.0</version>
</dependency>
  1. Create Kafka AdminClient
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.NewTopic;

import java.util.Collections;
import java.util.Properties;

public class CreateTopic {

    public static void main(String[] args) {
        // 创建Properties对象,并设置Kafka集群的地址
        Properties properties = new Properties();
        properties.put("bootstrap.servers", "localhost:9092");

        // 创建AdminClient对象
        AdminClient adminClient = AdminClient.create(properties);

        // 创建NewTopic对象,并设置主题名称和分区数
        NewTopic newTopic = new NewTopic("my-topic", 3);

        // 创建主题
        adminClient.createTopics(Collections.singletonList(newTopic));

        // 关闭AdminClient对象
        adminClient.close();
    }
}
  1. Run code
mvn exec:java
  1. Verify whether the topic is created successfully
kafka-topics --list --zookeeper localhost:2181

If you see my-topic topic means that the topic is created successfully.

Note

  • When creating a topic, you need to specify the topic name and number of partitions. The number of partitions determines how many messages a topic can process simultaneously.
  • When creating a topic, you can also specify other parameters, such as the number of copies, compression type, etc.
  • After creating a topic, you can send messages to the topic.
  • When consuming messages, you can specify a consumer group. The consumer group determines which consumers can consume the messages in the topic.

The above is the detailed content of Quick way to create a Kafka topic. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn