-
Notifications
You must be signed in to change notification settings - Fork 162
7. OrderService Microservice Create Kafka Producer
Ramesh Fadatare edited this page Jul 11, 2022
·
1 revision
package net.javaguides.orderservice.publisher;
import net.javaguides.basedomains.dto.Order;
import net.javaguides.basedomains.dto.OrderEvent;
import org.apache.kafka.clients.admin.NewTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
@Service
public class OrderProducer {
private Logger LOGGER = LoggerFactory.getLogger(OrderProducer.class);
private NewTopic topic;
private KafkaTemplate<String, Order> kafkaTemplate;
public OrderProducer(NewTopic topic, KafkaTemplate<String, Order> kafkaTemplate) {
this.topic = topic;
this.kafkaTemplate = kafkaTemplate;
}
public void sendMessage(OrderEvent orderEvent){
LOGGER.info(String.format("Order event sent to Kafka => %s", orderEvent.toString()));
Message<OrderEvent> message = MessageBuilder
.withPayload(orderEvent)
.setHeader(KafkaHeaders.TOPIC, topic.name())
.build();
kafkaTemplate.send(message);
}
}