Skip to content

Topic Exchange

Antoine Théate edited this page Jun 5, 2025 · 2 revisions

Exchange Explanation

Topic exchanges use pattern matching of the message's routing key to the routing (binding) key pattern used at binding time.

For the purpose of routing, the keys are separated into segments by .. Some segments are populated by specific values, while others are populated by wildcards: * for exactly one segment and # for zero or more (including multiple) segments

For example,

  • A binding (routing key) pattern of "regions.na.cities.*" will match message routing keys "regions.na.cities.toronto" and "regions.na.cities.newyork" but will not match "regions.na.cities" because * is a wildcard that matches exactly one segment
  • A binding (routing key) pattern "audit.events.#" will match "audit.events.users.signup" and "audit.events.orders.placed" but not "audit.users" because the second segment does not match
  • A binding (routing key) pattern of "#" will match any routing key and makes the topic exchange act like a fanout for the bindings that use such a pattern

Code Example

Micro Service A (Acts like consumer)

var messageClientService = serviceProvider.GetRequiredService<IMessageClientBaseService>();
var invalidListenConfiguration = new TopicExchangeConfiguration(exchangeName, "mercurio.topic.inf");
var messageObservable = await messageClientService.ListenAsync<string>("Primary", invalidListenConfiguration );
messageObservable.Subscribe(message => Console.WriteLine(message));

Micro Service B (Acts like producer and consumer)

var messageClientService = serviceProvider.GetRequiredService<IMessageClientBaseService>();
var pushExchangeConfiguration = new TopicExchangeConfiguration(exchangeName, "mercurio.topic.info");
var listenWithWildCardConfiguration = new TopicExchangeConfiguration(exchangeName, "mercurio.*.*");
var messageObservable = await messageClientService.ListenAsync<string>("Primary", listenWithWildCardConfiguration );
messageObservable.Subscribe(message => Console.WriteLine(message));
await messageClientService.PushAsync("Primary", "A message to be sent", pushExchangeConfiguration );

Results:
When the Micro Service B pushes the message, a new line will be written in the Console of Micro Service B with the content as "A message to be sent"

Clone this wiki locally