Skip to main content

Service Bus Queues from Windows Azure - How to separate message or specify a consumer what types of message to consume

I continue the series of posts about Service Bus Queues from Windows Azure with a new post about splitter and aggregator on this type of queue.
We should see in what cases we need something like this. One possible case is when we want to send large messages using Service Bus Queue. When we need to do something like this we should use a table or blob and only put a unique id on the queue. But let assume that this is not possible. The legal department doesn’t permit us to save the content of the message in another location. We can use only the Service Bus Queue from Windows Azure. In this case we need to split the content in more than one messages. If we do this, we will need a method to recombine the content. We don’t each consumer to receive a different part of the content. All the content should go only to one consumer.
Another case is when we want to be able to configure what kind of messages a consumer can handle. This can be done very easily with Service Bus Topics, but we have a solution using Service Bus Queues. The only limitation in this case is the number of types of messages a consumer can handle – only one. But we can filter the messages in a way that only one type of messages can be consumed by the Service Bus Queues.
The solution for both cases is the SessionId property of the BrokeredMessage. This is a string property that can be set to each BrokeredMessage. Using this property we can group messages based on a session id. I don’t imagine this as a session id, but like a grouped id. To this string we can set any kind of value, from a GUID to a date time or a group name.
Basically when we define the producer – the splitter – the only thing that we need to do different is to set the SessionId to a value.
QueueClient qc =
    QueueClient.CreateFromConnectionString(
    myFooConnectionString, "FooQueue");

BrokeredMessage message = new BrokeredMessage();
…
message.SessionId = Guid.NewGuid().ToString();
qc.Send(message);
In this example we set the session id property and after that we send the message to the queue. If we want the value of the SessionId can be a constant that can define the type of message. In the following example I split a stream in such way that we create n message that contain all the content of the stream even if the content would not fit in only one message.
Stream messageStream = message.GetBody<Stream>();
for (int offset = 0;
    offset < length;
    offset += 255)
        {                      
            long messageLength = (length - offset) > 255
                ? 255
        : length - offset;
            byte[] currentMessageContent = new byte[messageLength];
            int result = messageStream.Read(currentMessageContent, 0, (int)messageLength);
            BrokeredMessage currentMessage = new BrokeredMessage(
        new MemoryStream(currentMessageContent),
        true);
            subMessage.SessionId = currentContentId;
            qc.Send(currentMessage);
        }
The BrokeredMessage constructor accepts a stream as parameter. The second parameter specified in constructor is used to tell the framework to not close the stream after the message is send.
The big difference appear on the consumer side – aggregator. When we start to consume messages from a session we can receive only messages from that session. The QueueClient class contain a method named AcceptMessageSession(). This will return a MessageSession that will be used to receive message for the given session. AcceptMessageSession() permit us to specify the session id of to get the first session that is available.
In the following example we will see how we can consume only messages of a given type.
MessageSession messageSession = qc.AcceptMessageSession(mySessionId);
while(true)
{
    BrokeredMessage message = messageSession.Receive();
    ...
    message.Complete();
}
To be able to obtain the original stream we need to copy the content of each message to only one stream and in the end we will have our original stream – Service Bus Queue guarantees the order of the message will be the same as we send it (exception when a consumer don’t process a message as expected and the Complete() method is not called).
MemoryStream finalStream = new MemoryStream();
MessageSession messageSession = qc.AcceptMessageSession(mySessionId);
while(true)
{
    BrokeredMessage message = messageSession.Receive(TimeSpan.FromSeconds(20));
    if(message != null)
    {
                message.GetBody<Stream>().CopyTo(finalStream);
                message.Complete();
                continue;
    }
   break;
}

A consumer can consume more than one session id, but each on a different thread. On the same thread and in the same time this is not possible.
We saw how we can split the content in more than one BrokeredMessage and recreate the whole message on the other side using Service Bus Queues. In the next post about Service Bus Queues will talk about the limitation of this type of queue in comparison with Windows Azure Queues.

Comments

Popular posts from this blog

Windows Docker Containers can make WIN32 API calls, use COM and ASP.NET WebForms

After the last post , I received two interesting questions related to Docker and Windows. People were interested if we do Win32 API calls from a Docker container and if there is support for COM. WIN32 Support To test calls to WIN32 API, let’s try to populate SYSTEM_INFO class. [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision; } ... [DllImport("kernel32")] static extern void GetSystemInfo(ref SYSTEM_INFO pSI); ... SYSTEM_INFO pSI = new SYSTEM_INFO(...

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine: threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration: TeamCity .NET 4.51 EF 6.0.2 VS2013 It see...

Navigating Cloud Strategy after Azure Central US Region Outage

 Looking back, July 19, 2024, was challenging for customers using Microsoft Azure or Windows machines. Two major outages affected customers using CrowdStrike Falcon or Microsoft Azure computation resources in the Central US. These two outages affected many people and put many businesses on pause for a few hours or even days. The overlap of these two issues was a nightmare for travellers. In addition to blue screens in the airport terminals, they could not get additional information from the airport website, airline personnel, or the support line because they were affected by the outage in the Central US region or the CrowdStrike outage.   But what happened in reality? A faulty CrowdStrike update affected Windows computers globally, from airports and healthcare to small businesses, affecting over 8.5m computers. Even if the Falson Sensor software defect was identified and a fix deployed shortly after, the recovery took longer. In parallel with CrowdStrike, Microsoft provi...