I've been looking at MassTransit for a couple of weeks now and I'm curious about the possibilities. However, I don't seem to be able to get the concepts quite right.
Expected behaviour I wanted to publish message to "direct" exchange with routing key which is bind to two different queue for performing other activities.
When I attempted the same logic using MassTransit for better scalability. I've found MassTransit creates own exchange based on queue name with fanout type.
Classic code to publish message by exchange and routing key
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.ExchangeDeclare(exchange, "direct");
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange, routingKey, null, body);
Console.WriteLine(" [x] Sent {0}", message);
}
}
Is there a way to configure direct or topic exchange with routingkey in MassTransit?
Exchanges and Bindings Rules — or routing keys — enable you to bind queues to exchanges. RabbitMQ will try to match the routing key in the message to those used in the bindings. The message will then be delivered to the queue based on one of three types of exchange: fanout, topic, or direct.
Broker Topology With RabbitMQ, which supports exchanges and queues, messages are sent or published to exchanges and RabbitMQ routes those messages through exchanges to the appropriate queues. When the bus is started, MassTransit will create exchanges and queues on the virtual host for the receive endpoint.
MassTransit is a lightweight service bus for building distributed . NET applications. The main goal is to provide a consistent, . NET friendly abstraction over the message transport (whether it is RabbitMQ, Azure Service Bus, etc.).
Topic RabbitMQ exchange type sends messages to queues depending on wildcard matches between the routing key and the queue binding's routing pattern. Messages are routed to one or more queues based on a pattern that matches a message routing key. A list of words separated by a period must be used as the routing key (.).
Following code does the same work, but with one extra fanout exchange:
TestMessage (direct exchange) -> TestMessage_Queue(fanout exchange) -> TestMessage_Queue (queue)
var bus = Bus.Factory.CreateUsingRabbitMq(cfg =>
{
var host = cfg.Host(new Uri("rabbitmq://localhost"), h =>
{
h.Username("guest");
h.Password("guest");
});
cfg.Send<TestMessage>(x => { x.UseRoutingKeyFormatter(context => "routingKey"); });
cfg.Message<TestMessage>(x => x.SetEntityName("TestMessage"));
cfg.Publish<TestMessage>(x => { x.ExchangeType = ExchangeType.Direct; });
cfg.ReceiveEndpoint(host, "TestMessage_Queue", e =>
{
e.BindMessageExchanges = false;
e.Consumer<UpdateCustomerConsumer>();
e.Bind("TestMessage", x =>
{
x.ExchangeType = ExchangeType.Direct;
x.RoutingKey = "routingKey";
});
});
});
bus.Start();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With