1

一、背景

今天尝试使用 kafka 的 生产者 api 写一下,消息发送,结果遇到以下问题,
Topic xxx not present in metadata after 60000 ms,找了半天结果发现是jar包引入不全导致的,为防以后忘记,在此记录一下。

二、场景还原

1、jar包引入

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

2、jar代码

public class KafkaProducerDemo {

    public static void main(String[] args) {
        Properties properties = new Properties();

        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092,127.0.0.1:9093,127.0.0.1:9094");
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.ACKS_CONFIG, "all");
        properties.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432);
        properties.put(ProducerConfig.RETRIES_CONFIG, 0);
        properties.put(ProducerConfig.RETRY_BACKOFF_MS_CONFIG, 300);
        properties.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384);

        // KafkaProducer 是线程安全的,可以多个线程使用用一个 KafkaProducer
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties);
        for (int i = 0; i < 100; i++) {
            ProducerRecord<String, String> record = new ProducerRecord<>("topic-a", "value - (" + i + 1 + ")");
            kafkaProducer.send(record, new Callback() {
                @Override
                public void onCompletion(RecordMetadata metadata, Exception exception) {
                    if (exception != null) {
                        System.err.println("发送数据到kafka中,发生了异常.");
                        exception.printStackTrace();
                        return;
                    }
                    System.out.println("topic: " + metadata.topic() + " offset: " + metadata.offset() + " partition: "
                            + metadata.partition());
                }
            });
        }

        System.out.println("消息发送完成");
        kafkaProducer.close();
    }
}

3、运行结果

运行结果
运行上面的代码出现了 org.apache.kafka.common.errors.TimeoutException: Topic topic-a not present in metadata after 60000 ms 异常。

三、问题解决

其实这个问题很简单,在启动项目的时候加入 logback.xml 配置文件,然后加入logback相关的jar包,发现,缺少jackson的jar,引入之后就好了。

<dependency>
    <groupId>org.apache.kafka</groupId>
    <artifactId>kafka-clients</artifactId>
    <version>2.6.0</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.0</version>
</dependency>

四、参考文档

1、https://stackoverflow.com/questions/63714401/org-apache-kafka-common-errors-timeoutexception-topic-not-present-in-metadata-a

2、http://kafka.apache.org/26/documentation.html#producerapi


huan1993
207 声望31 粉丝

java工程师