Producing Kafka messages

The event producer publishes the domain events to the message hub. This happens synchronously to rely on the messages being in the system. Once the transmission is acknowledged, the EventProducer#publish method invocation returns:

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;

@ApplicationScoped
public class EventProducer {

    private Producer<String, MealEvent> producer;
    private String topic;

    @Inject
    Properties kafkaProperties;

    @PostConstruct
    private void init() {
        producer = new KafkaProducer<>(kafkaProperties);
        topic = kafkaProperties.getProperty("topics.order");
        producer.initTransactions();
    }

    public void publish(MealEvent event) {
        ProducerRecord<String, MealEvent> record = new ProducerRecord<>(topic, event);
        try {
            producer.beginTransaction();
            producer.send(record);
            producer.commitTransaction();
        } catch (ProducerFencedException e) {
            producer.close();
        } catch (KafkaException e) {
            producer.abortTransaction();
        }
    }

    @PreDestroy
    public void close() {
        producer.close();
    }
}

Going into the details of the Kafka producer API is beyond the scope of this book. However, it needs to be ensured that the events are sent reliably. The event producer bean encapsulates this logic.

These examples demonstrate one possibility for integrating Kafka.

As mentioned earlier, the Java EE Connector Architecture (JCA) is another possibility for integrating external concerns into the application container. At the time of writing, there are vendor-specific container solutions that integrate messaging via JCA. Existing solutions for integrating message hubs such as Kafka are an interesting alternative. However, application developers are advised to encapsulate technology specifics into single points of responsibilities and use standard Java EE functionality within the application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.119.106