How Do I connect in two RabbitMQ servers using MassTransit

Viewed 172

How can I open two connections working with massTransit To RabbitMQ servers?

Today I'm working with one connection, but I need to create more consumers in anothers Server:

services.AddMassTransit(x =>
{ 
    //this consumer will get messages from one Exchange, and I need to create
    //another consumers from anothers Exchanges.
    x.AddConsumer<OptionExecutedConsumer>();
    
    x.UsingRabbitMq((context, cfg) =>
    {
        cfg.Host(rabbitMQConfig.Connection.Servers[0],
        rabbitMQConfig.Connection.Port,
        rabbitMQConfig.Connection.VirtualHost,
        h =>
        {
            h.Username(rabbitMQConfig.Connection.Username);
            h.Password(rabbitMQConfig.Connection.Password);
            h.UseCluster(c =>
            {
                rabbitMQConfig.Connection.Servers.ToList()
                    .ForEach(server => c.Node(server));
            });
        });
        cfg.ReceiveEndpoint(rabbitMQConfig.Consumer.OptionExerciseQueue, e =>
        {
            e.UseRetry(r =>
                r.Incremental(rabbitMQConfig.Consumer.RetryLimit,
                TimeSpan.FromSeconds(rabbitMQConfig.Consumer.InitialInterval),
                TimeSpan.FromSeconds(rabbitMQConfig.Consumer.IntervalIncrement)));
    
            e.Bind(rabbitMQConfig.Consumer.OptionExerciseExchange, x =>
            {
                e.ConcurrentMessageLimit = 1;
                e.DiscardFaultedMessages();
                e.ClearMessageDeserializers();
                e.UseRawJsonSerializer();
                e.ConfigureConsumer<OptionExecutedConsumer>(context);
            });
        });      
    });
});

How can I create new connections using this class? Is there a best pratice to do this?

1 Answers

You need to set up two separate bus instances. It was always possible but wasn't very DI-friendly. At the moment, the multi-bus feature, which is well-documented allows you to do exactly that pretty easily.

Related