Search code examples
spring-bootrabbitmqspring-amqp

How to intercept authentication errors in RabbitMQ


We have a company policy that when we have authentication failures for more than 3 times in a row, the account gets locked. In the Spring Boot service we have setup using RabbitMQ, the login mechanism to establish a connection happens automatically. In such case, if the username and password does not match, this causes an account lock. So, we want to have an interceptor which checks if the connection can be made by trying once or twice. If the connection does not work, then we can integrate it to a health check and alert accordingly. I checked the existing retry properties, but it seems to be related to message delivery and processing. Is there any mechanism to prevent automatic connections to RabbitMQ?


Solution

  • There are two type of services to connect to RabbitMQ: producer (RabbitTemplate) which is passive and does not connect until you try to use its API. Another one is a consumer which is an active component and has a polling loop in its own thread. This one starts automatically by default when application is ready. However you can make it not doing that setting its autoStartup to false.

    So, what you need in your project logic is to have all the Rabbit listeners as non-started by default, do not send any messages to RabbitTemplate, until your health service turn the switch respectively.

    Your check interceptor probably just could use ConnectionFactory.createConnection().createChannel(false).exchangeDeclarePassive("amq.direct") to be sure that connection is OK and so on.