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(...

How to audit an Azure Cosmos DB

In this post, we will talk about how we can audit an Azure Cosmos DB database. Before jumping into the problem let us define the business requirement: As an Administrator I want to be able to audit all changes that were done to specific collection inside my Azure Cosmos DB. The requirement is simple, but can be a little tricky to implement fully. First of all when you are using Azure Cosmos DB or any other storage solution there are 99% odds that you’ll have more than one system that writes data to it. This means that you have or not have control on the systems that are doing any create/update/delete operations. Solution 1: Diagnostic Logs Cosmos DB allows us activate diagnostics logs and stream the output a storage account for achieving to other systems like Event Hub or Log Analytics. This would allow us to have information related to who, when, what, response code and how the access operation to our Cosmos DB was done. Beside this there is a field that specifies what was th...

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills)

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills) The idea that moving to the cloud reduces the costs is a common misconception. The cloud infrastructure provides flexibility, scalability, and better CAPEX, but it does not guarantee lower costs without proper optimisation and management of the cloud services and infrastructure. Idle and unused resources, overprovisioning, oversize databases, and unnecessary data transfer can increase running costs. The regional pricing mode, multi-cloud complexity, and cost variety add extra complexity to the cost function. Cloud adoption without a cost governance strategy can result in unexpected expenses. Improper usage, combined with a pay-as-you-go model, can result in a nightmare for business stakeholders who cannot track and manage the monthly costs. Cloud-native services such as AI services, managed databases, and analytics platforms are powerful, provide out-of-the-shelve capabilities, and increase business agility and innovation. H...