添加依賴
testImplementation "org.springframework.kafka:spring-kafka-test"
配置 KafkaTemplate
@Configuration
public class KafkaConfig {
@Autowired
EmbeddedKafkaBroker broker;
@Bean
public KafkaTemplate<String, String> template() {
return new KafkaTemplate<>(new DefaultKafkaProducerFactory<>(KafkaTestUtils.producerProps(broker)));
}
}
添加測試
@SpringBootTest
@EmbeddedKafka
public class KafkaTest {
private static final Logger log = LoggerFactory.getLogger(KafkaTest.class);
@Autowired
EmbeddedKafkaBroker broker;
@Autowired
KafkaTemplate<String, String> template;
@Test
void kafka() throws InterruptedException, ExecutionException {
log.info("start send");
ListenableFuture<SendResult<String, String>> future = template
.send("topic1", "time: " + System.currentTimeMillis());
future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
@Override
public void onFailure(Throwable throwable) {
log.error("onFailure", throwable);
}
@Override
public void onSuccess(SendResult<String, String> stringStringSendResult) {
log.info("onSuccess {}", stringStringSendResult);
}
});
log.info("result: {}", future.get());
}
}
使用 @KafkaListener 接收消息
修改註解
// 創建topic
@EmbeddedKafka(topics = "topic1")
// 覆蓋配置
@TestPropertySource(properties = {"spring.kafka.bootstrap-servers=${spring.embedded.kafka.brokers}",
// 消費更早的消息,因爲可能消息已經發送但是bean還沒註冊
"spring.kafka.consumer.auto-offset-reset=earliest"})
添加監聽
@KafkaListener(id = "webGroup1", topics = "topic1")
public void listen(ConsumerRecord<String, String> input) {
log.info("input value: {}", input);
}