我的服务器使用docker安装kafka:wurstmeister / kafka。
当我使用kafka-clients 2.2.0生成和使用kafka消息时, 我的生产者运作良好,但消费者没有收到任何消息。
但是当我使用shell时,此命令无法获得消息:
/opt/kafka_2.12-2.2.0/bin/kafka-console-consumer.sh --bootstrap-server 10.2.0.242:9092 --topic mytesttopic --from-beginning
此命令可以获取所有消息:
/opt/kafka_2.12-2.2.0/bin/kafka-console-consumer.sh --bootstrap-server 10.2.0.242:9092 --topic mytesttopic --from-beginning --partition 0
String kafkaServer = "10.2.0.242:9092";
String defaultTopic = "mytesttopic";
// create topic
Properties props = new Properties();
props.put("bootstrap.servers", kafkaServer);
try (AdminClient client = AdminClient.create(props)) {
CreateTopicsResult ret = client.createTopics(Arrays.asList(new NewTopic(defaultTopic, 1, (short) 1)));
ret.all().get();
}
// send message
props.put("acks", "all");
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
KafkaProducer producer = new KafkaProducer<String, String>(props);
ProducerRecord<String, String> msg = new ProducerRecord<>(defaultTopic, "a1", "test1");
Future ret = producer.send(msg);
System.out.println("send ok: " + ret.get());
// recieve message
props = new Properties();
props.put("bootstrap.servers", kafkaServer);
props.put("group.id", "testaaa4aaa");
props.put("enable.auto.commit", "false");
props.put("auto.offset.reset", "earliest");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer consumer = new KafkaConsumer<String, String>(props);
TopicPartition partition1 = new TopicPartition(defaultTopic, 0);
consumer.assign(Arrays.asList(partition1));
// consumer.subscribe(Arrays.asList(defaultTopic));
Duration duration = Duration.ofMillis(100);
while (true) {
ConsumerRecords<String, String> records = consumer.poll(duration);
// here always get 0.
System.out.println(records.count());
}
我尝试在代码中设置TopicPartition,但仍然无法收到消息,有人可以帮助我吗?
答案 0 :(得分:0)
如控制台消息所述,您的组协调器似乎不可用。您最近是否更新/更改了Docker映像?事实是,如果您未指定group.id
或为控制台使用者手动指定了分区,则说明您未使用Kafka的组管理(因此没有协调器)。因此,这可以解决问题。如果您使用其他组ID会怎样?