Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuring ConnectionFactory for RabbitMQ in Spring Boot AMQP

TL;DR How to create Spring Boot AMQP connection factory programatically?

Hey,

In order to connect to my RabbitMQ I added these to my application.properties file of my Spring Boot app:

spring.rabbitmq.host=host
spring.rabbitmq.port=5672
spring.rabbitmq.username=myapp
spring.rabbitmq.password=mypass

And according to my understanding, these values are then used to create Spring Boot's auto configured ConnectionFactory, which I then use in:

@Bean
@Conditional(RabbitCondition.class)
SimpleMessageListenerContainer container(ConnectionFactory connectionFactory, MessageListenerAdapter completedOrderListenerAdapter) {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    container.setConnectionFactory(connectionFactory);
    container.setQueueNames(completedOrderQueueName);
    container.setMessageListener(completedOrderListenerAdapter);
    return container;
}

I would like to be able to use rabbitMQ credentials from different environment files which are not application.properties, so I would like to create ConnectionFactory bean programatically. How do I achieve this?

Thanks.

like image 267
Airwavezx Avatar asked Jan 02 '19 07:01

Airwavezx


1 Answers

@Bean
public ConnectionFactory connectionFactory() {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
    connectionFactory.setAddresses(address);
    connectionFactory.setUsername(username);
    connectionFactory.setPassword(password);
    return connectionFactory;
}
like image 153
mkjh Avatar answered Oct 15 '22 00:10

mkjh