RabbitMQ RPC across multiple rabbitMQ instances

安稳与你 提交于 2019-11-29 03:40:56

Take a look at org.springframework.amqp.rabbit.connection.AbstractRoutingConnectionFactory. It will allow you to create multiple connection factories to different vhosts or different rabbitmq instances. We are using it for a multi tenant rabbitmq application.

It's been awhile, but if you're using Spring you can create as many connection factories as you want, with their own configurations (host, user/pass, vhost, etc.), just like you did:

@Bean
@Primary
public ConnectionFactory amqpConnectionFactory1() {
    final CachingConnectionFactory connectionFactory = new CachingConnectionFactory();

    connectionFactory.setAddresses("...");
    connectionFactory.setUsername("...");
    connectionFactory.setPassword("...");
    connectionFactory.setVirtualHost("...");

    return connectionFactory;
}

@Bean
public ConnectionFactory amqpConnectionFactory2() {
    final CachingConnectionFactory connectionFactory = new CachingConnectionFactory();

    // ...

    return connectionFactory;
}

And your rabbit admin/template's as you go:

@Bean
@Primary
public RabbitAdmin rabbitAdmin1() {
    return new RabbitAdmin(amqpConnectionFactory1());
}

@Bean
public RabbitAdmin rabbitAdmin2() {
    return new RabbitAdmin(amqpConnectionFactory2());
}

// ...

@Bean
@Primary
public RabbitTemplate rabbitTemplate1() {
    RabbitTemplate rabbitTemplate = new RabbitTemplate(amqpConnectionFactory1());

    // ...

    return rabbitTemplate;
}

@Bean
public RabbitTemplate rabbitTemplate2() {
    RabbitTemplate rabbitTemplate = new RabbitTemplate(amqpConnectionFactory2());

    // ...

    return rabbitTemplate;
}

Note that you have to provide the @Primary tag to enable one main bean, once Spring doesn't know which one to choose when you don't inform the name explicitly.

With this in hands, just inject them normally along your components:

@Autowired
private RabbitTemplate template;

// ...

@Autowired
@Qualifier("rabbitTemplate2") // Needed when want to use the non-primary bean
private RabbitTemplate template;

Hope it helps! :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!