Content Based Routing (CBR) is another pattern used in the integration world. The contents of the message determines the endpoint of the message.
This article will describe one option to develop this pattern using an Azure Service Bus, an Azure Function and a Logic App.
Basically the service bus will be used to route the message to the correct endpoint using topics and subscriptions. The Azure Function is used to host and execute the business rules to inspect the message contents and set the routing properties. A logic app is used to accept the message and call the function passing the received message as an argument. Once the function executes the business rules, it will return the routing properties in the response body. The routing information is then used to set the properties on the service bus API connector in the Logic App before publishing the message onto the bus.
Scenario
To demonstrate a typical use-case of this pattern we have 2 message types, Sales Orders (SO) and Purchase Orders (PO). For the SO I want to send the order to a priority queue if the total sales amount is over a particular value. And for a PO, it should be sent to a pre-approval queue if the order value is under a specified amount.
Here is an example of a SO message to be routed:
And an example of a PO being sent:
Solution
The real smarts of this solution is the function which will return a common JSON response message to set the values for the Topic name and the custom properties on the service bus connector. The fields of the response message are described below.
- TopicName – the name of service bus topic to send the message to.
- CBRFilter_1 – used by the subscription rule to filter the value on. Depending on your own requirements you may need more fields to filter more granular.
- RuleSetVersion – used by the subscription rule to filter the value on. It’s a good idea to have this field as you may have several versions of this rule in play at any one time.
Let’s start with provisioning the service bus topics and subscriptions for the 2 types of messages. First create 2 topics called purchaseorder and salesorder.
Now add the following subscriptions and rules for each of the topics.
Topic Name | Subscription Name | Rule |
purchaseorder | Approved_V1.00 | CBRFilter_1 = ‘Approved’ and RuleSetVersion = ‘1.00’ |
purchaseorder | NotApproved_V1.00 | CBRFilter_1 = ‘ApprovedNot’ and RuleSetVersion = ‘1.00’ |
salesorder | HighPriority_V1.00 | CBRFilter_1 = ‘PriorityHigh’ and RuleSetVersion = ‘1.00’ |
salesorder | LowPriority_V1.00 | CBRFilter_1 = ‘PriorityLow’ and RuleSetVersion = ‘1.00’ |
Next is the development of the Azure function. This is best developed in Visual Studio where you can include a Unit Test project to each of the rules. Add a new Azure Function project to your solution.
After the project has been created, right click on the function and click Add -> New Item. Choose Azure Function, give it a name and select the Http trigger option.
Below is code for the HTTP trigger function which includes the class definition for the RoutingProperties object. I am checking for specific elements SalesOrderNumber, PurchaseOrderNumber in the JSON message to determine the type of message and which determines what rule code block to execute. Each rule block code will first set the TopicName and RuleSetVersion properties.
public static class CBRRule
{
[FunctionName("CBRRule")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
var routingProperties = new RoutingProperties();
// Get request body
JObject data = await req.Content.ReadAsAsync<JObject>();
//Is this a sales order message type
if (data != null && data["SalesOrderNumber"] != null)
{
routingProperties.CBRFilter_1 = "PriorityLow";
routingProperties.RuleSetVersion = "1.00";
routingProperties.TopicName = "SalesOrder";
var lineItems = data["Lines"];
var totalSaleAmount = lineItems.Sum(x => (decimal)x["UnitPrice"] * (decimal)x["Qty"]);
//if the total sales is greater than $1000 send the message to the high priority queue
if (totalSaleAmount > 1000)
routingProperties.CBRFilter_1 = "PriorityHigh";
}
//Is this a purchase order message type
if (data != null && data["PurchaseOrderNumber"] != null)
{
routingProperties.CBRFilter_1 = "ApprovedNot";
routingProperties.RuleSetVersion = "1.00";
routingProperties.TopicName = "PurchaseOrder";
var lineItems = data["Lines"];
var totalSaleAmount = lineItems.Sum(x => (decimal)x["UnitPrice"] * (decimal)x["Qty"]);
//Approve PO if the total order price is less than $500
if (totalSaleAmount < 500)
routingProperties.CBRFilter_1 = "Approved";
}
return req.CreateResponse(HttpStatusCode.OK, routingProperties);
}
/// <summary>
/// Response message to set the custom routing properties of the service bus
/// </summary>
public class RoutingProperties
{
public string TopicName { get; set; }
public string CBRFilter_1 { get; set; }
public string RuleSetVersion { get; set; }
public RoutingProperties()
{
this.CBRFilter_1 = "Unknown";
this.RuleSetVersion = "Unknown";
this.TopicName = "Unknown";
}
}
}
The business rule for a SO aggregates all the line items and checks if the total amount is greater than 1000, if it is then set the property CBRFilter_1 to “PriorityHigh”.
The business rule for a PO also aggregates all the line items and checks if the total amount is less than 500, if it is then set the property CBRFilter to “Approved”.
With the following input message sent to the function:
The output of the function should look similar to this below
Now we need to publish the function from Visual Studio to your Azure resource group using the publishing wizard.
The last component of this solution is the Logic App which is triggered by an HTTP Request API and then calls the Azure function created above. The basic flow looks like this below.
The HTTP Request trigger has no request body JSON schema created. The trigger must accept any type of message.
Add an Azure Function after the trigger action and select the method called “CBRRule”
Set the Request Body to the trigger body content and the Method to “POST”
Next add a Service Bus action and set the properties as shown. Both the Queue/Topic name and Properties are set from the function response message
Here is the code view of the Send Message action showing how the properties are set.
Testing
Using PostMan we can send sample messages to the Logic App and then see them sitting on the service bus waiting to be processed by some other method.
At the moment the service bus should have no messages waiting to be processed as shown
Using PostMan to send the following PO, we should see this message end up in the purchaseorder/NotApproved subscription.
All going well, the message will arrive at the correct subscription waiting to be processed as shown below using Service Bus Explorer.
Sending the following SO will also route the message to the correct subscriber.
Conclusion
CBR can be easily achievable using an Azure Function to execute your business rules on a message to set up the routing properties. Taking this a step further, I would abstract the business rules for each message type in its own class for manageability.
Also it is advisable to setup a Unit Test project for each of the classes holding the business rules to ensure 100% code testing coverage.
Enjoy…