我有一个Kafka制作人,我用Java编写过。尽管它基本上是示例代码的剪切和过去,但它似乎不能正常工作。我希望输出为我的群集的10条消息。相反,我得到消息成功输出但实际上没有任何内容进入我的群集。我不知道从哪里开始排除故障。
import java.util.Properties;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
public class SimpleProducer {
public static void main(String[] args) throws Exception{
String topicName = "test_topic";
Properties props = new Properties();
props.put("bootstrap.servers", "skynet.local:6667");
props.put("acks", "all");
props.put("retries", 0);
props.put("batch.size", 16384);
props.put("linger.ms", 1);
props.put("buffer.memory", 33554432);
props.put("key.serializer","org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer","org.apache.kafka.common.serialization.StringSerializer");
Producer<String, String> producer = new KafkaProducer<String, String>(props);
for(int i = 0; i < 10; i++)
producer.send(new ProducerRecord<String, String>(topicName, Integer.toString(i), Integer.toString(i)));
System.out.println("Message sent successfully");
producer.close();
}
}
答案 0 :(得分:2)
由于某些环境未清除,因此我将尝试回答您的问题,因为您的Kafka服务器已在使用端口6667。
您的代码可能需要在2个位置进行调整(有人可以帮我改进):
props.put("linger.ms", 1); // set to 0 let Producer can send message immediately
在这里,从producer.close();
循环中删除for
:
Producer<String, String> producer = new KafkaProducer<String, String>(props, new StringSerializer(), new StringSerializer());
for(int i = 0; i < 10; i++) {
Future<RecordMetadata> f = producer.send(new ProducerRecord<String, String>(topicName, Integer.toString(i), Integer.toString(i)));
System.out.println(f.get()); // don't do that in your Production, here just for debugging purpose.
}
producer.close();
还有一件事,您可以在测试之前运行kafka-console-consumer.sh
和kafka-console-producer.sh
以确认您的Kafka服务器并且您的SimpleProducer已经正常运行。 Kafka Producer Configuration Parameters