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(

Azure AD and AWS Cognito side-by-side

In the last few weeks, I was involved in multiple opportunities on Microsoft Azure and Amazon, where we had to analyse AWS Cognito, Azure AD and other solutions that are available on the market. I decided to consolidate in one post all features and differences that I identified for both of them that we should need to take into account. Take into account that Azure AD is an identity and access management services well integrated with Microsoft stack. In comparison, AWS Cognito is just a user sign-up, sign-in and access control and nothing more. The focus is not on the main features, is more on small things that can make a difference when you want to decide where we want to store and manage our users.  This information might be useful in the future when we need to decide where we want to keep and manage our users.  Feature Azure AD (B2C, B2C) AWS Cognito Access token lifetime Default 1h – the value is configurable 1h – cannot be modified

What to do when you hit the throughput limits of Azure Storage (Blobs)

In this post we will talk about how we can detect when we hit a throughput limit of Azure Storage and what we can do in that moment. Context If we take a look on Scalability Targets of Azure Storage ( https://azure.microsoft.com/en-us/documentation/articles/storage-scalability-targets/ ) we will observe that the limits are prety high. But, based on our business logic we can end up at this limits. If you create a system that is hitted by a high number of device, you can hit easily the total number of requests rate that can be done on a Storage Account. This limits on Azure is 20.000 IOPS (entities or messages per second) where (and this is very important) the size of the request is 1KB. Normally, if you make a load tests where 20.000 clients will hit different blobs storages from the same Azure Storage Account, this limits can be reached. How we can detect this problem? From client, we can detect that this limits was reached based on the HTTP error code that is returned by HTTP