mercredi 27 mars 2019

Is it correct to encapsulate KafkaTemplate/handling methods in your own wrapper(and how)?

I try to introduce apache Kafka to our project and change projects architecture to producer-consumer. I experiment on a new test project. For example, I have one producer and two consumers. It is different spring-boot applications(microservices).

In producer service, I need to configure Kafka, create KafkaTemplate. In each consumer, I need to configure Kafka and create handlers(methods with @KafkaListener annotation).

For example, tomorrow we will want to change Kafka to something another, we will change KafkaTemplate and methods with @KafkaListener annotation to an implementation of a new library. This is not a good approach. So I consider that we need to create our wrapper. Something like this:

public interface EventBus {
    void sendMessage(String topicName, String message);
}

And encapsulate KafkaTemplate in the implementation of this interface(KafkaEventBus implements EventBus)

I start to implement it but I faced the fact that I do not understand how to do it. I create a Gradle module with 'event-bus' name. This module is not spring - just java module. I create EventBus interface and implement it:

public class KafkaEventBus implements EventBus {

    private final KafkaProducer<String, String> kafkaProducer;

    public KafkaEventBus() {
        this.kafkaProducer = new KafkaProducer<>(producerConfig());
    }

    @Override
    public void sendMessage(String topicName, String message) {
        kafkaProducer.send(new ProducerRecord<>(topicName,message));
    }

    private Map<String, Object> producerConfig() {
        Map<String, Object> configProps = new HashMap<>();
        configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        return configProps;
    }
}

And stuck. I have questions:

1) Do I need to create a different module(event-bus)? Do I think right?

2) How can implement message handling in this module? If sending something is clear(encapsulate KafkaTemplate and delegate message to it) then with handling ничего не понятно nothing is clear.

Maybe, Are there some examples of this, best practices?

Aucun commentaire:

Enregistrer un commentaire