在Spring Boot AMQP中为RabbitMQ配置ConnectionFactory

时间:2019-01-02 07:41:56

标签: java spring-boot rabbitmq spring-amqp

TL; DR 如何以编程方式创建Spring Boot AMQP连接工厂?

为了连接到RabbitMQ,我将它们添加到了我的Spring Boot应用程序的application.properties文件中:

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

根据我的理解,然后将这些值用于创建Spring Boot的自动配置ConnectionFactory,然后将其用于:

@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;
}

我希望能够使用不是application.properties的不同环境文件中的RabbitMQ凭证,所以我想以编程方式创建ConnectionFactory bean。 我该如何实现?

谢谢。

1 个答案:

答案 0 :(得分:2)

@Bean
public ConnectionFactory connectionFactory() {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
    connectionFactory.setAddresses(address);
    connectionFactory.setUsername(username);
    connectionFactory.setPassword(password);
    return connectionFactory;
}