[英]Consumer unit test with poll() never receives anything
考慮以下代碼:
@Test(singleThreaded = true)
public class KafkaConsumerTest
{
private KafkaTemplate<String, byte[]> template;
private DefaultKafkaConsumerFactory<String, byte[]> consumerFactory;
private static final KafkaEmbedded EMBEDDED_KAFKA;
static {
EMBEDDED_KAFKA = new KafkaEmbedded(1, true, "topic");
try { EMBEDDED_KAFKA.before(); } catch (final Exception e) { e.printStackTrace(); }
}
@BeforeMethod
public void setUp() throws Exception {
final Map<String, Object> senderProps = KafkaTestUtils.senderProps(EMBEDDED_KAFKA.getBrokersAsString());
senderProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
senderProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class);
final ProducerFactory<String, byte[]> pf = new DefaultKafkaProducerFactory<>(senderProps);
this.template = new KafkaTemplate<>(pf);
this.template.setDefaultTopic("topic");
final Map<String, Object> consumerProps = KafkaTestUtils.consumerProps("sender", "false", EMBEDDED_KAFKA);
this.consumerFactory = new DefaultKafkaConsumerFactory<>(consumerProps);
this.consumerFactory.setValueDeserializer(new ByteArrayDeserializer());
this.consumerFactory.setKeyDeserializer(new StringDeserializer());
}
@Test
public void testSendToKafka() throws InterruptedException, ExecutionException, TimeoutException {
final String message = "42";
final Message<byte[]> msg = MessageBuilder.withPayload(message.getBytes(StandardCharsets.UTF_8)).setHeader(KafkaHeaders.TOPIC, "topic").build();
this.template.send(msg).get(10, TimeUnit.SECONDS);
final Consumer<String, byte[]> consumer = this.consumerFactory.createConsumer();
consumer.subscribe(Collections.singleton("topic"));
final ConsumerRecords<String, byte[]> records = consumer.poll(10000);
Assert.assertTrue(records.count() > 0);
Assert.assertEquals(new String(records.iterator().next().value(), StandardCharsets.UTF_8), message);
consumer.commitSync();
}
}
我正在嘗試將消息發送到KafkaTemplate
並使用Consumer.poll()
再次閱讀。 我正在使用的測試框架是TestNG 。
發送作品時,我已驗證使用在網絡中找到的“常用”代碼(在KafkaMessageListenerContainer
上注冊消息偵聽KafkaMessageListenerContainer
)。
只是,我從未在消費者中收到任何東西。 我已經針對“真正的” Kafka安裝嘗試了相同的序列(create Consumer
, poll()
),並且可以正常工作。
因此,看來我設置ConsumerFactory
的方式有問題嗎? 任何幫助將不勝感激!
您需要使用
EMBEDDED_KAFKA.consumeFromAnEmbeddedTopic(consumer, "topic");
在通過KafkaTemplate
發布記錄之前。
然后在測試驗證結束時,您需要使用以下代碼:
ConsumerRecord<String, String> record = KafkaTestUtils.getSingleRecord(consumer, "topic");
您也可以按照自己的方式使用它,因為缺少的只是earliest
的ConsumerConfig.AUTO_OFFSET_RESET_CONFIG
,因為默認值是latest
。 這樣,以后添加到該主題的使用者就不會看到以前發布的任何記錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.