I have one publisher and one consumer for my Service Bus topic. My goal is to make the consumer receive messages in the same order that the publisher published them to the topic. Here is my code to publish messages to a session-enabled topic:
public void Publish<T>(T messageObject)
{
var jsonString = JsonSerializer.Serialize(messageObject);
var message = new ServiceBusMessage(jsonString)
{
SessionId = "12345"
};
message.ApplicationProperties["messageType"] = typeof(T).Name;
serviceBusSender.SendMessageAsync(message);
}
And here is the code for the receiver:
public async Task ReceiveWithSessionsAsync()
{
var options = new ServiceBusSessionProcessorOptions
{
ReceiveMode = ServiceBusReceiveMode.ReceiveAndDelete,
AutoCompleteMessages = true,
MaxConcurrentSessions = 1,
MaxConcurrentCallsPerSession = 1,
};
await using ServiceBusSessionProcessor processor = serviceBusClient.CreateSessionProcessor("my_topic", "my_subscription__session_enabled", options);
processor.ProcessMessageAsync += MessageHandler;
async Task MessageHandler(ProcessSessionMessageEventArgs args)
{
var body = args.Message.Body.ToString();
logger.LogInformation($"received body: {body}");
}
// start processing
await processor.StartProcessingAsync();
}
I make several calls to Publish
and then call ReceiveWithSessionsAsync
, however, the order of messages received still is not the same order by which they were sent.
What am I missing here?
Answering my own question in case anyone else runs into this.
So I realized the problem was not in the consumer since the messages on the Service Bus Explorer showed the messages were in the wrong order.
What I was missing was an await
on serviceBusSender.SendMessageAsync(message)
call, off course without awaiting this async call, the order of messages would be random. SMH!