简体   繁体   中英

No error or output records when running Kafka producer

I have the below kafka producer code and When I run it I don't see any error and the records are not showing up in the consumer console. I am using https://kafka.apache.org/quickstart to start the zookeeper, broker. I created a topic and started the consumer.

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

public class SampleProducerCreator {

    Properties properties =  new Properties();

    private void init(){
        properties.setProperty("bootstrap.servers", "localhost:9092");
        properties.setProperty("kafka.topic.name", "quickstart-events");
        KafkaProducer<String, String> producer = new KafkaProducer<>(this.properties,
                new StringSerializer(), new StringSerializer());
        for(int i=0; i<4 ; i++){
            String payload = "Test";
            ProducerRecord<String, String> record = new ProducerRecord<>(properties.getProperty("kafka.topic.name"), payload);
            producer.send(record);
        }
        producer.close();
    }

   public static void main(String[] args){
        SampleProducerCreator sampleProducerCreator = new SampleProducerCreator();
        sampleProducerCreator.init();
   }
}

There may be connectivity issues to the broker. If no slf4j implementation is added to your java project, logs won't be printed.

Also, producer.send(record) returns a future. You can use this future to block and wait for a response, or better use the alternative send(record, callback) javadoc to print out the exception or record metadata returned by the broker.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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