How to use the same QueueTrigger method for reading/handling messages from different Azure Message Queues using INameResolver
The Azure WebJob SDK provides a lot of helper functionalities that we can leverage. One example is the QueueTrigger API, that provides the ability to read messages from a queue when a message comes in. Just as a comparison, if you are not using the QueueTrigger API, you will probably have to write some timer, and/or loop code to read messages from a queue periodically. This is not fun. Let's take a look at a usage example below.
public class Foo { ... public void ProcessMessage([QueueTrigger("MyQueueName")] string message) { // Do something with message. ... }
The code above is pretty self explanatory. This class will be invoked when a message appears on "MyQueueName". However, what if we want to handle a bunch of messages coming from different queue names? Would we have to repeat this code in a couple of places? Certainly not! We can handle this by implementing INameResolver.
public class NameResolver : INameResolver { ... public string Resolve(string name) { if (name == "thisQueue") { return "MyQueueName"; } if (name == "thatQueue") { return "MyQueueName"; }
In order to leverage the NameResolver, we will have to set it in the job host configuration.
var jobHostConfiguration = new JobHostConfiguration { ... NameResolver = new NameResolver(new NameResolver ()) };
Now, all we have to do is to add the percentage symbols and we are good to go. Any messages that comes in from thisQueue or thatQueue will be routed to this handler.
public class Foo { ... public void ProcessMessage([QueueTrigger("%MyQueueName%")] string message) { // Do something with message. ... }
As an additional note, if you are wondering how I was able to get my class to work without making it a static class/method, I am actually using AutoFac to orchestrate the instantiation of this class. I will probably write another article about it later. Do leave me some comments below if you like this article or if it helps you out.
This comment has been removed by the author.
ReplyDeleteI found your article while trying to understand why my INameResolver is not actually invoked with multiple queues.
ReplyDeleteAny suggestion why it does not work as it should?
I would check to make sure the code in JobHostConfiguration is setup correctly. Try to set a breakpoint where you have JobHostConfiguration and ensure the breakpoint is hit there.
DeleteYour code is wrong, in facts INameResolver.Resolve() does just the opposite: it is called by with parameter name = %placeholder% used in QueueTrigger declaration and returns the actual queue name in Azure storage account. You should not write such things but go climb a tree instead
Delete