SENDING MESSAGES WITH A TOPIC QUEUE IN RABBITMQ
Setting up a topic queue
If you haven’t done so already, have a look at how you set up the direct queue here:
SETTING UP A TOPIC QUEUE IN RABBITMQ.
The code
public void SendMessage(MqMessage message)
{
_channel.BasicPublish(
exchange: "TopicExchange",
routingKey: "homeelectronics.*.sales",
basicProperties: null,
body: ObjectSerialize.Serialize(message));
}
public static byte[]? Serialize(object? obj) =>
null != obj
? Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(obj))
: null;
The code explained
_channel.BasicPublish(
exchange: "TopicExchange",
routingKey: "homeelectronics.music.sales",
basicProperties: null,
body: ObjectSerialize.Serialize(message));
Sending data is easy. Just call the BasicPublish() method on the channel.
To send a message with Topic queues, we use both the Exchange name and the Routing Key to connect the sender and the receiver. The queue is declared when we set up the queue, remember?
The routing key is then used to say what topic we’re broadcasting.
And just a quick note, sending messages cannot use wildcards (* or #). They are only available when we filter what we will receive.
public static byte[]? Serialize(object? obj) =>
null != obj
? Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(obj))
: null;
The data we want to send is stored in objects. Now, RabbitMQ can’t handle every conceivable class in the world, it’s just not practical. Or even possible.
RabbitMQ is a generic system, and it as such, needs a generic way of sending data. So it’s up to us to turn our objects into that uniform data type. That’s why we convert it to a byte array.
— Cheers!