Skip to content

Lib Usage

Júlio Falbo edited this page Dec 1, 2019 · 6 revisions

We have an example project in this repo that you can see how to use this lib for publishers and listeners.

Publisher

This lib has a class called RabbitTemplateHandler and uses it is very simple. We just need to call the getRabbitTemplate method and pass the virtual host as a parameter for getting the correct bean of RabbitTemplate. Once with this bean, you can call the convertAndSend method and pass the exchange and the routing key as parameters.

Note: You can get the exchange and the routing key using the @Value annotation.

Example:

@Value("${spring.rabbitmq.custom.some-event.exchange}")
private String exchangeSomeEvent;

@Value("${spring.rabbitmq.custom.some-event.queueRoutingKey}")
private String routingKeySomeEvent;

@Autowired
private final RabbitTemplateHandler rabbitTemplateHandler;

public void sendMessage(final String message) {
    rabbitTemplateHandler.getRabbitTemplate("some-event").convertAndSend(exchangeSomeEvent, routingKeySomeEvent, message);
}

Listener

To listeners is very simple too. The only thing that you need to do is annotate a method with the RabbitListener annotation and pass the name of containerFactory.

How do I know the name of the correct container factory for each virtual host?

You don't need to know, just pass the name of your event and the library will do the magic for you!

This lib also has an option to enable the retry and dlq strategy, that is recommended to use.

To enable this behavior is very simple, we just need to annotate our method with the EnableRabbitRetryAndDlq annotation and pass the nome of the property as an argument.

Note: You also have an option to specify which exceptions you want to enable the retry and dlq strategy. By default, the value is Exception.class, which means that all exceptions will be handled.

Example:

@RabbitListener(containerFactory = "some-event", queues = "${spring.rabbitmq.custom.some-event.queue}")
@EnableRabbitRetryAndDlq(event = "some-event",
retryWhen = { IllegalArgumentException.class, RuntimeException.class },
discardWhen = { NullPointerException.class },
directToDlqWhen = NumberFormatException.class)
public void onMessage(Message message) {
    ...
}
Clone this wiki locally