kafka错误之 Topic xxx not present in metadata after 60000 ms

一、背景

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

二、场景还原

1、jar包引入


    org.apache.kafka
    kafka-clients
    2.6.0

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 kafkaProducer = new KafkaProducer<>(properties);
        for (int i = 0; i < 100; i++) {
            ProducerRecord 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、运行结果

kafka错误之 Topic xxx not present in metadata after 60000 ms_第1张图片
运行上面的代码出现了 org.apache.kafka.common.errors.TimeoutException: Topic topic-a not present in metadata after 60000 ms 异常。

三、问题解决

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


    org.apache.kafka
    kafka-clients
    2.6.0


    com.fasterxml.jackson.core
    jackson-databind
    2.12.0

四、参考文档

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

你可能感兴趣的:(kafka,java,后端)