Reputation: 832
How to set up RabbitMQ clients/queues/exchanges for following scenario (in .Net)? I have one server (lets call it server1
) which is running many services (service1
, service2
...) and multiple clients (client1
, client2
, clientN
). I want messages generated by server1
's service1
to be sent to all clients which are listening for messages from service1
.
I managed to do that but I have one issue - apparently, although the message is received by client listening on exchange/queue service1
and AutoACK
is enabled, messages are not removed - when next one comes, old ones arrive again and clients Received
events fires as many times as there were previous messages.
I need minimal example for server/producer (one sending messages) and example for clients which receive messages based on some routing key. If there is no clients listening for that specific routing key, never mind, message can be dropped. Routing key is known in advance by both server and client, so specific client "knows" that he wants to receive messages from service2
.
Current setup is this:
Client code (this one listens all messages, that's the reason why the routing key is "#" - some clients have defined routing key - service1
and so on.
servicesChannel = conn.CreateModel();
servicesChannel.ExchangeDeclare("services", ExchangeType.Fanout);
var queueName = servicesChannel.QueueDeclare().QueueName;
servicesChannel.QueueBind(queue: queueName, exchange: "services", routingKey: "#");
var consumer = new EventingBasicConsumer(servicesChannel);
consumer.Received += (model, ea) =>
{
// do bunch of stuff before
log.Trace("Acknowledging message " + ea.DeliveryTag);
// if we uncomment this, no more messages will arrive after 1st!
//servicesChannel.BasicAck(ea.DeliveryTag, false);
}
servicesChannel.BasicConsume(queue: queueName, autoAck: true, consumer: consumer);
And server's code, pushing messages:
servicesChannel= conn.CreateModel();
servicesChannel.ExchangeDeclare("services", ExchangeType.Fanout);
...
string message = Newtonsoft.Json.JsonConvert.SerializeObject(data, settings);
var body = Encoding.UTF8.GetBytes(message);
servicesChannel.BasicPublish(exchange: "services", routingKey: routingKey, basicProperties: null, body: body);
Upvotes: 1
Views: 1712
Reputation: 1556
What you are search on is the Topics exchange.
Beside my comment about you publish to a different exchange.
You exchange declare must be:
servicesChannel.ExchangeDeclare("services", type: "topic");
Read more and see code example here: https://www.rabbitmq.com/tutorials/tutorial-five-dotnet.html
Upvotes: 0