Stef Heyenrath
Stef Heyenrath

Reputation: 9830

How to use multiple vhosts in a Spring RabbitMQ project?

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 ?

Upvotes: 1

Views: 9506

Answers (2)

Lyju I Edwinson
Lyju I Edwinson

Reputation: 1834

We can achieve this using SimpleRoutingConnectionFactory, where we create multiple connection factories each for a vhost and configure it to SimpleRoutingConnectionFactory.

From the spring documentation: spring doc

public class MyService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void service(String vHost, String payload) {
        SimpleResourceHolder.bind(rabbitTemplate.getConnectionFactory(), vHost);
        rabbitTemplate.convertAndSend(payload);
        SimpleResourceHolder.unbind(rabbitTemplate.getConnectionFactory());
    }

}

I have created a git repo showing how to do this: spring-boot-amqp-multiple-vhosts

Upvotes: 1

Gary Russell
Gary Russell

Reputation: 174554

See conditional declaration.

Specifically:

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

Upvotes: 2

Related Questions