Common message broker interface for Kafka and ActiveMQ
I want to design an interface which would be used for simple sending and receiving messages between spring boot micro services. Any service should be able to autowire the interface and use send/receive methods. The implementation of those methods should depend upon, say application.props file whether it wants to use kafka or activemq. I am not able to come up with a clean design. I was thinking if I could create a custom annotation for it. With whatever spring boot experience I have I am not able to imagine such a design. The skeleton looks like something below but I am not able to see how will I be able to implement this as proper code: beans, switch between kafka/activemq specific annotations and methods, etc. things like that.
Service:
@Autowired MessageProducer messageProducer
@Autowired MessageReceiver messageReceiver
MessageProducer [interface] public void sendMessage(destination, payload)
MessageReceiver [interface] public void receiveMessage(source, payload)
you could have two implementation classes like KafkaMessageProducer
and ActvieMQMessageProducer
. inside application.properties
you could have config like messaging.type=kafka
or messaging.type=activemq
that will specify which messaging communication should application select.
Configuration class:
@Configuration public class MessagingConfiguration { @Bean @ConditionalOnProperty(name = "messaging.type", havingValue = "kafka") public MessageProducer messageProducer() { return new KafkaMessageProducer(); } @Bean @ConditionalOnProperty(name = "messaging.type", havingValue = "activemq") public MessageProducer messageProducer() { return new ActvieMQMessageProducer(); } }
if you want to use both messaging types in the same application (e.g. one service class will use Kafka meanwhile another class will use ActiveMQ), then create two beans (as mentioned above, but with @Qualifier
and without @ConditionalOnProperty
). And on each service, that require message producer, specify with @Qualifier
which implementation you need
@Configuration public class MessagingConfiguration { @Bean @Qualifier("kafkaMessageProducer") public MessageProducer messageProducer() { return new KafkaMessageProducer(); } @Bean @Qualifier("actvieMQMessageProducer") public MessageProducer messageProducer() { return new ActvieMQMessageProducer(); } @Bean public YourService messageProducer(@Qualifier("kafkaMessageProducer") MessageProducer messageProducer) { return new YourServiceImpl(messageProducer); } }