Spring Boot
Spring Boot + Spring Kafka producer and consumer examples.
Other LInks
Setup
Run spring boot:
gradle kafka-spring-boot:bootRun
Produce
Spring has the class KafkaTemplate
that allows you to produce messages.
@Value("${spring.kafka.topic}")
private String topic;
@Autowired
private KafkaTemplate<String, Customer> kafkaTemplate;
public void sendCustomer(Customer customer) {
log.info("Producing message: {}", customer);
kafkaTemplate.send(topic, customer.getId().toString(), customer);
}
In another terminal:
http :8585/produce messages==10
Consume
You can use the KafkaListener
annotation.
@KafkaListener(topics = { "${spring.kafka.topic}" })
public void consume(ConsumerRecord<String, Customer> record) {
log.info("Customer ID: {}", record.value());
}