How to use multiple vhosts in a Spring RabbitMQ pr

2019-07-25 03:05发布

问题:

I've the following two Configuration classes:

@Configuration
@EnableRabbit
@Import({ LocalRabbitConfigA.class, CloudRabbitConfigA.class })
public class RabbitConfigA {
    @Autowired
    @Qualifier("rabbitConnectionFactory_A")
    private ConnectionFactory rabbitConnectionFactory;

    @Bean(name = "admin_A")
    AmqpAdmin amqpAdmin() {
        return new RabbitAdmin(rabbitConnectionFactory);
    }

    @Bean(name = "Exchange_A")
    DirectExchange receiverExchange() {
        return new DirectExchange("Exchange_A", true, false);
    }
}

And

@Configuration
@EnableRabbit
@Import({ LocalRabbitConfigB.class, CloudRabbitConfigB.class })
public class RabbitConfigB {
    @Autowired
    @Qualifier("rabbitConnectionFactory_B")
    private ConnectionFactory rabbitConnectionFactory;

    @Bean(name = "admin_B")
    AmqpAdmin amqpAdmin() {
        return new RabbitAdmin(rabbitConnectionFactory);
    }

    @Bean(name = "Exchange_B")
    DirectExchange receiverExchange() {
        return new DirectExchange("Exchange_B", true, false);
    }
}

Note that the LocalRabbitConfigA and LocalRabbitConfigB classes define the connectionFactory which connects to a different VHost.
When starting the application (within Tomcat), all the Exchanges are created in both VHosts.

The question is how to define that a certain Exchange/Queue is created by a specific ConnectionFactiory ?

So that VHost A contains only the Exchange_A, and VHost B only Exchange_B ?

回答1:

See conditional declaration.

Specifically:

@Bean(name = "Exchange_B")
DirectExchange receiverExchange() {
    DirectExchange exchange = new DirectExchange("Exchange_B", true, false);
    exchange.setAdminsThatShouldDeclare(amqpAdmin());
    return exchange;
}