SENDING MESSAGES WITH A DIRECT QUEUE IN RABBITMQ
Setting up a direct queue
If you haven’t done so already, have a look at how you set up the direct queue here:
SETTING UP A DIRECT QUEUE IN RABBITMQ.
The code
_channel.BasicPublish(
exchange: ””,
routingKey: ”DirectQueue”,
basicProperties: null,
body: ObjectSerialize.Serialize(message));
public static byte[]? Serialize(object? obj) =>
null != obj
? Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(obj))
: null;
Receiving messages with a Direct queue
The code explained
_channel.BasicPublish(
exchange: ””,
routingKey: ”DirectQueue”,
basicProperties: null,
body: ObjectSerialize.Serialize(message));
Sending data is easy. Just call the BasicPublish() method on the channel.
To send a message with Direct queues, we use the Routing Key to connect the sender and the receiver. They both just have to agree on a Routing Key, and RabbitMQ will take care of the rest.
That’s why we set the Exchange parameter to an empty string. Actually, it will automatically assign one under the hood. But you will never see it.
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!