问题描述
我有下面的kafka生产者代码,当我运行它时,我没有看到任何错误,并且记录未显示在使用者控制台中。我正在使用https://kafka.apache.org/quickstart启动Zookeeper经纪人。我创建了一个主题并开始了消费者。
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();
}
}
解决方法
可能存在与代理的连接问题。如果未将slf4j实现添加到您的Java项目中,则不会打印日志。
此外,producer.send(record)
返回未来。您可以使用此Future来阻止并等待响应,或者更好地使用备用send(record,callback)
javadoc打印出异常或记录代理返回的元数据。