Created
February 1, 2022 13:28
-
-
Save mmafrar/13269808444e86680d4e3eb67f0dab06 to your computer and use it in GitHub Desktop.
Getting Started with Apache Kafka and Spring Boot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.kafka; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.kafka.core.KafkaTemplate; | |
import org.springframework.kafka.support.SendResult; | |
import org.springframework.stereotype.Service; | |
import org.springframework.util.concurrent.ListenableFuture; | |
import org.springframework.util.concurrent.ListenableFutureCallback; | |
@Service | |
public class Producer { | |
private static final String TOPIC = "purchases"; | |
private static final Logger logger = LoggerFactory.getLogger(Producer.class); | |
@Autowired | |
private KafkaTemplate<String, String> kafkaTemplate; | |
public void sendMessage(String key, String value) { | |
ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(TOPIC, key, value); | |
future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() { | |
@Override | |
public void onSuccess(SendResult<String, String> result) { | |
logger.info(String.format("Produced event to topic %s: key = %-10s value = %s", TOPIC, key, value)); | |
} | |
@Override | |
public void onFailure(Throwable ex) { | |
ex.printStackTrace(); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment