简体   繁体   English

我们如何使用 API 从 IDE 在 Kafka 中创建主题

[英]How Can we create a topic in Kafka from the IDE using API

How Can we create a topic in Kafka from the IDE using API because when I do this:我们如何使用 API 从 IDE 在 Kafka 中创建主题,因为当我这样做时:

bin/kafka-create-topic.sh --topic mytopic --replica 3 --zookeeper localhost:2181

I get the error:我收到错误:

bash: bin/kafka-create-topic.sh: No such file or directory

And I followed the developer setup as it is.我按照原样遵循了开发人员设置。

In Kafka 0.8.1+ -- the latest version of Kafka as of today -- you can programmatically create a new topic via AdminCommand .在 Kafka 0.8.1+(目前最新版本的 Kafka)中,您可以通过AdminCommand编程方式创建新主题。 The functionality of CreateTopicCommand (part of the older Kafka 0.8.0) that was mentioned in one of the previous answers to this question was moved to AdminCommand .在此问题的先前答案之一中提到的CreateTopicCommand (旧版 Kafka 0.8.0 的一部分)的功能已移至AdminCommand

Scala example for Kafka 0.8.1: Kafka 0.8.1 的 Scala 示例:

import kafka.admin.AdminUtils
import kafka.utils.ZKStringSerializer
import org.I0Itec.zkclient.ZkClient

// Create a ZooKeeper client
val sessionTimeoutMs = 10000
val connectionTimeoutMs = 10000
// Note: You must initialize the ZkClient with ZKStringSerializer.  If you don't, then
// createTopic() will only seem to work (it will return without error).  The topic will exist in
// only ZooKeeper and will be returned when listing topics, but Kafka itself does not create the
// topic.
val zkClient = new ZkClient("zookeeper1:2181", sessionTimeoutMs, connectionTimeoutMs,
    ZKStringSerializer)

// Create a topic named "myTopic" with 8 partitions and a replication factor of 3
val topicName = "myTopic"
val numPartitions = 8
val replicationFactor = 3
val topicConfig = new Properties
AdminUtils.createTopic(zkClient, topicName, numPartitions, replicationFactor, topicConfig)

Build dependencies, using sbt as example:构建依赖,以 sbt 为例:

libraryDependencies ++= Seq(
  "com.101tec" % "zkclient" % "0.4",
  "org.apache.kafka" % "kafka_2.10" % "0.8.1.1"
    exclude("javax.jms", "jms")
    exclude("com.sun.jdmk", "jmxtools")
    exclude("com.sun.jmx", "jmxri"),
  ...
)

EDIT: Added Java example for Kafka 0.9.0.0 (latest version as of Jan 2016).编辑:为 Kafka 0.9.0.0 添加了 Java 示例(截至 2016 年 1 月的最新版本)。

Maven dependencies: Maven 依赖项:

<dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka_2.11</artifactId>
    <version>0.9.0.0</version>
</dependency>
<dependency>
    <groupId>com.101tec</groupId>
    <artifactId>zkclient</artifactId>
    <version>0.7</version>
</dependency>

Code:代码:

import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.ZkConnection;

import java.util.Properties;

import kafka.admin.AdminUtils;
import kafka.utils.ZKStringSerializer$;
import kafka.utils.ZkUtils;

public class KafkaJavaExample {

  public static void main(String[] args) {
    String zookeeperConnect = "zkserver1:2181,zkserver2:2181";
    int sessionTimeoutMs = 10 * 1000;
    int connectionTimeoutMs = 8 * 1000;
    // Note: You must initialize the ZkClient with ZKStringSerializer.  If you don't, then
    // createTopic() will only seem to work (it will return without error).  The topic will exist in
    // only ZooKeeper and will be returned when listing topics, but Kafka itself does not create the
    // topic.
    ZkClient zkClient = new ZkClient(
        zookeeperConnect,
        sessionTimeoutMs,
        connectionTimeoutMs,
        ZKStringSerializer$.MODULE$);

    // Security for Kafka was added in Kafka 0.9.0.0
    boolean isSecureKafkaCluster = false;
    ZkUtils zkUtils = new ZkUtils(zkClient, new ZkConnection(zookeeperConnect), isSecureKafkaCluster);

    String topic = "my-topic";
    int partitions = 2;
    int replication = 3;
    Properties topicConfig = new Properties(); // add per-topic configurations settings here
    AdminUtils.createTopic(zkUtils, topic, partitions, replication, topicConfig);
    zkClient.close();
  }

}

EDIT 2: Added Java example for Kafka 0.10.2.0 (latest version as of April 2017).编辑 2:为 Kafka 0.10.2.0 添加了 Java 示例(截至 2017 年 4 月的最新版本)。

Maven dependencies: Maven 依赖项:

<dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka_2.11</artifactId>
    <version>0.10.2.0</version>
</dependency>
<dependency>
    <groupId>com.101tec</groupId>
    <artifactId>zkclient</artifactId>
    <version>0.9</version>
</dependency>

Code:代码:

import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.ZkConnection;

import java.util.Properties;

import kafka.admin.AdminUtils;
import kafka.admin.RackAwareMode;
import kafka.utils.ZKStringSerializer$;
import kafka.utils.ZkUtils;

public class KafkaJavaExample {

  public static void main(String[] args) {
    String zookeeperConnect = "zkserver1:2181,zkserver2:2181";
    int sessionTimeoutMs = 10 * 1000;
    int connectionTimeoutMs = 8 * 1000;

    String topic = "my-topic";
    int partitions = 2;
    int replication = 3;
    Properties topicConfig = new Properties(); // add per-topic configurations settings here

    // Note: You must initialize the ZkClient with ZKStringSerializer.  If you don't, then
    // createTopic() will only seem to work (it will return without error).  The topic will exist in
    // only ZooKeeper and will be returned when listing topics, but Kafka itself does not create the
    // topic.
    ZkClient zkClient = new ZkClient(
        zookeeperConnect,
        sessionTimeoutMs,
        connectionTimeoutMs,
        ZKStringSerializer$.MODULE$);

    // Security for Kafka was added in Kafka 0.9.0.0
    boolean isSecureKafkaCluster = false;

    ZkUtils zkUtils = new ZkUtils(zkClient, new ZkConnection(zookeeperConnect), isSecureKafkaCluster);
    AdminUtils.createTopic(zkUtils, topic, partitions, replication, topicConfig, RackAwareMode.Enforced$.MODULE$);
    zkClient.close();
  }

}

As of 0.11.0.0 all you need is:从 0.11.0.0 开始,您只需要:

<dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka-clients</artifactId>
    <version>0.11.0.0</version>
</dependency>

This artifact now contains the AdminClient ( org.apache.kafka.clients.admin ).这个工件现在包含AdminClient ( org.apache.kafka.clients.admin )。

AdminClient can handle many Kafka admin tasks, including topic creation: AdminClient可以处理许多 Kafka 管理任务,包括主题创建:

Properties config = new Properties();
config.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "kafka:9092");

AdminClient admin = AdminClient.create(config);

Map<String, String> configs = new HashMap<>();
int partitions = 1;
int replication = 1;

admin.createTopics(asList(new NewTopic("topic", partitions, replication).configs(configs)));

The output of this command is a CreateTopicsResult , which you can use to get a Future for the whole operation or for each individual topic creation:此命令的输出是一个CreateTopicsResult ,您可以使用它来获取整个操作或每个单独主题创建的Future

  • to get a future for the whole operation, use CreateTopicsResult#all() .要获得整个操作的未来,请使用CreateTopicsResult#all()
  • to get Future s for all the topics individually, use CreateTopicsResult#values() .要单独获取所有主题的Future ,请使用CreateTopicsResult#values()

For example:例如:

CreateTopicsResult result = ...
KafkaFuture<Void> all = result.all();

or:要么:

CreateTopicsResult result = ...
for (Map.Entry<String, KafkaFuture<Void>> entry : result.values().entrySet()) {
    try {
        entry.getValue().get();
        log.info("topic {} created", entry.getKey());
    } catch (InterruptedException | ExecutionException e) {
        if (Throwables.getRootCause(e) instanceof TopicExistsException) {
            log.info("topic {} existed", entry.getKey());
        }
    }
}

KafkaFuture is "a flexible future which supports call chaining and other asynchronous programming patterns," and "will eventually become a thin shim on top of Java 8's CompletebleFuture ." KafkaFuture是“一个支持调用链和其他异步编程模式的灵活未来”,并且“最终将成为 Java 8 CompletebleFuture之上的一个薄垫片”。

For creating a topic through java api and Kafka 0.8+ try the following,要通过 java api 和 Kafka 0.8+ 创建主题,请尝试以下操作,

First import below statement首先导入下面的语句

import kafka.utils.ZKStringSerializer$;

Create object for ZkClient in the following way,通过以下方式为 ZkClient 创建对象,

ZkClient zkClient = new ZkClient("localhost:2181", 10000, 10000, ZKStringSerializer$.MODULE$);
AdminUtils.createTopic(zkClient, myTopic, 10, 1, new Properties());

You can try with kafka.admin.CreateTopicCommand scala class to create Topic from Java code...providng the necessary arguments.您可以尝试使用 kafka.admin.CreateTopicCommand scala 类从 Java 代码创建主题...提供必要的参数。

String [] arguments = new String[8];
arguments[0] = "--zookeeper";
arguments[1] = "10.***.***.***:2181";
arguments[2] = "--replica";
arguments[3] = "1";
arguments[4] = "--partition";
arguments[5] = "1";
arguments[6] = "--topic";
arguments[7] = "test-topic-Biks";

CreateTopicCommand.main(arguments);

NB: You should add the maven dependencies for jopt-simple-4.5 & zkclient-0.1注意:您应该为jopt-simple-4.5zkclient-0.1添加 maven 依赖jopt-simple-4.5

Based on the latest kafka-client api and Kafka 2.1.1, the working version of code follows:基于最新的kafka-client api和Kafka 2.1.1,工作版本代码如下:

Import the latest kafka-clients using sbt.使用 sbt 导入最新的 kafka 客户端。

// https://mvnrepository.com/artifact/org.apache.kafka/kafka-clients
libraryDependencies += Seq("org.apache.kafka" % "kafka-clients" % "2.1.1",
"org.apache.kafka" %% "kafka" % "2.1.1")

The code for topic creation in scala: scala中创建主题的代码:

import java.util.Arrays
import java.util.Properties

import org.apache.kafka.clients.admin.NewTopic
import org.apache.kafka.clients.admin.{AdminClient, AdminClientConfig}

class CreateKafkaTopic {
  def create(): Unit = {
    val config = new Properties()
    config.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "192.30.1.5:9092")

    val localKafkaAdmin = AdminClient.create(config)

    val partitions = 3
    val replication = 1.toShort
    val topic = new NewTopic("integration-02", partitions, replication)
    val topics = Arrays.asList(topic)

    val topicStatus = localKafkaAdmin.createTopics(topics).values()
    //topicStatus.values()
    println(topicStatus.keySet())
  }

}

Validate the new topic using:使用以下方法验证新主题:

./kafka-topics.sh --zookeeper 192.30.1.5:2181 --list

Hope it is helpful to someone.希望它对某人有帮助。 Reference: http://kafka.apache.org/21/javadoc/index.html?org/apache/kafka/clients/admin/AdminClient.html参考: http : //kafka.apache.org/21/javadoc/index.html?org/apache/kafka/clients/admin/AdminClient.html

If you are using Kafka 0.10.0.0+, creating topic from Java requires passing parameter of RackAwareMode type.如果您使用的是 Kafka 0.10.0.0+,从 Java 创建主题需要传递 RackAwareMode 类型的参数。 It's a Scala case object, and getting it's instance from Java is tricky (proof: How do I "get" a Scala case object from Java? for example. But it is not applicable for our case).这是一个 Scala case 对象,从 Java 获取它的实例很棘手(证明: 我如何从 Java “获取”一个 Scala case 对象?例如。但它不适用于我们的情况)。

Luckily, rackAwareMode is an optional parameter.幸运的是,rackAwareMode 是一个可选参数。 Yet Java does not support optional parameters.然而 Java 不支持可选参数。 How do we solve that?我们如何解决这个问题? Here is a solution:这是一个解决方案:

AdminUtils.createTopic(zkUtils, topic, 1, 1, 
    AdminUtils.createTopic$default$5(),
    AdminUtils.createTopic$default$6());

Use it with miguno's answer, and you are good to go.将它与 miguno 的答案一起使用,您就可以开始了。

From Kafka 0.8 Producer Example the sample below will create a topic named page_visits and also start producing if the auto.create.topics.enable attribute is set to true (default) in the Kafka Broker config file从 Kafka 0.8 Producer Example下面的示例将创建一个名为page_visits的主题,并且如果 Kafka Broker 配置文件中的auto.create.topics.enable属性设置为true (默认),也会开始生产

import java.util.*;

import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;

public class TestProducer {
    public static void main(String[] args) {
        long events = Long.parseLong(args[0]);
        Random rnd = new Random();

        Properties props = new Properties();
        props.put("metadata.broker.list", "broker1:9092,broker2:9092 ");
        props.put("serializer.class", "kafka.serializer.StringEncoder");
        props.put("partitioner.class", "example.producer.SimplePartitioner");
        props.put("request.required.acks", "1");

        ProducerConfig config = new ProducerConfig(props);

        Producer<String, String> producer = new Producer<String, String>(config);

        for (long nEvents = 0; nEvents < events; nEvents++) { 
            long runtime = new Date().getTime();  
            String ip = “192.168.2.” + rnd.nextInt(255); 
            String msg = runtime + “,www.example.com,” + ip; 
            KeyedMessage<String, String> data = new KeyedMessage<String, String>("page_visits", ip, msg);
            producer.send(data);
        }
        producer.close();
   }
}

A few ways your call wouldn't work.你的电话有几种方式不起作用。

  1. If your Kafka cluster didn't have enough nodes to support a replication value of 3.如果您的 Kafka 集群没有足够的节点来支持复制值 3。

  2. If there is a chroot path prefix you have to append it after the zookeeper port如果有 chroot 路径前缀,则必须将其附加到 zookeeper 端口之后

  3. You arent in the Kafka install directory when running (This is the most likely)运行时您不在Kafka安装目录中(这是最有可能的)

There is AdminZkClient which we can use to manage topics in Kafka server.我们可以使用AdminZkClient来管理 Kafka 服务器中的主题。

String zookeeperHost = "127.0.0.1:2181";
Boolean isSucre = false;
int sessionTimeoutMs = 200000;
int connectionTimeoutMs = 15000;
int maxInFlightRequests = 10;
Time time = Time.SYSTEM;
String metricGroup = "myGroup";
String metricType = "myType";
KafkaZkClient zkClient = KafkaZkClient.apply(zookeeperHost,isSucre,sessionTimeoutMs,
                connectionTimeoutMs,maxInFlightRequests,time,metricGroup,metricType);

AdminZkClient adminZkClient = new AdminZkClient(zkClient);

String topicName1 = "myTopic";
int partitions = 3;
int replication = 1;
Properties topicConfig = new Properties();

adminZkClient.createTopic(topicName1,partitions,replication,
            topicConfig,RackAwareMode.Disabled$.MODULE$);

You can refer this link for details https://www.analyticshut.com/streaming-services/kafka/create-and-list-kafka-topics-in-java/您可以参考此链接了解详情https://www.analyticshut.com/streaming-services/kafka/create-and-list-kafka-topics-in-java/

From which IDE are your trying ?您正在尝试使用哪个 IDE?

Please provide complete path , below are the command from terminal which will create a topic请提供完整路径,下面是来自终端的命令,它将创建一个主题

  1. cd kafka/bin
  2. ./kafka-create-topic.sh --topic test --zookeeper localhost:2181

As of Kafka 0.10.1 the ZKStringSerializer mentioned by Michael is private (for Scala).从 Kafka 0.10.1 开始,Michael 提到的 ZKStringSerializer 是私有的(对于 Scala)。 You can use the factory methods createZkClient or createZkClientAndConnection in ZkUtils.您可以在 ZkUtils 中使用工厂方法 createZkClient 或 createZkClientAndConnection。

Scala example for Kafka 0.10.1: Kafka 0.10.1 的 Scala 示例:

import kafka.utils.ZkUtils

val sessionTimeoutMs = 10000
val connectionTimeoutMs = 10000
val (zkClient, zkConnection) = ZkUtils.createZkClientAndConnection(
  "localhost:2181", sessionTimeoutMs, connectionTimeoutMs) 

Then just create the topic as Michael suggested:然后按照迈克尔的建议创建主题:

import kafka.admin.AdminUtils

val zkUtils = new ZkUtils(zkClient, zkConnection, false)
val numPartitions = 4
val replicationFactor = 1
val topicConfig = new Properties
val topic = "my-topic"
AdminUtils.createTopic(zkUtils, topic, numPartitions, replicationFactor, topicConfig)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM