Flow Control in Mule 4

Flow Control in Mule 4
Flow Control in Mule 4

In Mule, Flow Controls helps you route your input Mule Event into one or more separate flows based on the flow control components you use. Mule offers four connectors to achieve flow control.

1) First Successful

2) Round Robin

3) Choice Router

4) Scatter-Gather

Flow Control connectors are also called Routers as their main task is to take the input Mule event and route it to one or more separate sequences of components.

First Successful

The First Successful router iterates through a list of configured processing routes until one of the routes executes successfully. If any processing route fails execution (throws an error), the router executes the next configured route.

Round Robin

Round Robin is a Mule component that contains two or more processing routes and executes only one of the routes each time the flow executes the component. Each route within Round Robin is a scope that can contain one or more processors.

The term round-robin is derived from the French term ruban ('ribbon'). Over time, the term became idiomized to Robin. In a single round-robin schedule, each participant plays every other participant once.

Choice Router

The Choice router dynamically routes messages through a flow according to a set of Dataweave expressions that evaluate message content. Each expression is associated with a different routing option.

Difference between Choice and First successful
Choice router will always have an expression for when block and when all of the expressions are false then it will go with default block. But in the case of First Successful, it iterates through its list of child routes, each containing a set of components, until the first successful execution.

Scatter-Gather

The Scatter-Gather component is a routing event processor that processes a Mule event through different parallel processing routes that contain different event processors. Each route receives a reference to the Mule event and executes a sequence of one or more event processors.

Here is the working example for flow control in mule 4.

<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:db="http://www.mulesoft.org/schema/mule/db" xmlns:email="http://www.mulesoft.org/schema/mule/email"
	xmlns:http="http://www.mulesoft.org/schema/mule/http"
	xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/email http://www.mulesoft.org/schema/mule/email/current/mule-email.xsd
http://www.mulesoft.org/schema/mule/db http://www.mulesoft.org/schema/mule/db/current/mule-db.xsd">
	<http:request-config name="HTTP_Request_configuration" doc:name="HTTP Request configuration" doc:id="f838ef3d-0717-4f19-a9db-bedd4b3e0d6c" basePath="/v3.1" >
		<http:request-connection protocol="HTTPS" host="restcountries.com" port="443" />
	</http:request-config>
	<db:config name="Database_Config" doc:name="Database Config" doc:id="0173b131-5664-45be-b6ad-adcb8ee33267" >
		<db:generic-connection url="${secure::db.url}" driverClassName="${secure::db.name}" user="${secure::db.user}" password="${secure::db.passwordl}" />
	</db:config>
		<email:smtp-config name="Email_SMTP" doc:name="Email SMTP" doc:id="d1a805e3-6803-4d30-a0b6-27aa41d94745" >
		<email:smtp-connection host="${smtp.host}" port="${smtp.port}" user="${secure::smtp.user}" password="${secure::smtp.password}" >
			<email:properties >
				<email:property key="mail.smtp.starttls.enable" value="true" />
			</email:properties>
		</email:smtp-connection>
	</email:smtp-config>
	<flow name="flow_controlFlow" doc:id="964eea80-7933-4071-aef7-15e346c2f6d6" >
		<scheduler doc:name="Scheduler for 2mins" doc:id="02e86f92-54f7-4b15-842b-c6331fd46314" >
			<scheduling-strategy >
				<fixed-frequency frequency="2" timeUnit="MINUTES"/>
			</scheduling-strategy>
		</scheduler>
		<logger level="INFO" doc:name="Start Logger" doc:id="9ac2b5b1-ef0d-4801-a623-df37f78a9ce1" message="flow started successfully"/>
		<round-robin doc:name="Round Robin" doc:id="6d5d35fb-bd45-4ca7-aade-b23d95ed585e" >
			<route >
				<set-variable value='#["India"]' doc:name="Set Country as India" doc:id="d70c2387-3033-4c38-914f-628ad08ac706" variableName="Country"/>
			</route>
			<route >
				<set-variable value='#["Japan"]' doc:name="Set Country as Japan " doc:id="509acbc0-30fd-40b5-a19d-6834d65fe963" variableName="Country "/>
			</route>
		</round-robin>
		<first-successful doc:name="First Successful" doc:id="f114f075-9033-4348-b44f-16929fcff5bf" >
			<route >
				<http:request method="GET" doc:name="restcountries_api" doc:id="4834184a-8d09-437d-a4ef-1dbc15a4edbf" config-ref="HTTP_Request_configuration" path="/name/{nam}">
			<http:uri-params><![CDATA[#[output application/java
---
{
	"name" : vars.Country
}]]]></http:uri-params>
		</http:request>
			</route>
			<route >
				<http:request method="GET" doc:name="restcountries_api" doc:id="08113abe-f24f-4876-96b9-14cc71933299" config-ref="HTTP_Request_configuration" path="/name/{name}">
			<http:uri-params><![CDATA[#[output application/java
---
{
	"name" : vars.Country
}]]]></http:uri-params>
		</http:request>
			</route>
			<route >
				<http:request method="GET" doc:name="restcountries_api1" doc:id="b7015980-d749-4d86-adfe-577a43bdd6d1" config-ref="HTTP_Request_configuration" path="/name/{name}">
			<http:uri-params><![CDATA[#[output application/java
---
{
	"name" : vars.Country
}]]]></http:uri-params>
		</http:request>
			</route>
		</first-successful>
		<choice doc:name="Fetching captial for requested country's" doc:id="8682e433-5eb0-4080-8a54-0fcb7ef7f422" >
			<when expression='#[vars.Country == "India"]'>
				<ee:transform doc:name="response payload" doc:id="e2133598-0aa3-400a-9313-a5cf1e9fd00a" >
					<ee:message >
						<ee:set-payload ><![CDATA[%dw 2.0
output application/json
---
payload.capital[1] joinBy  ""]]></ee:set-payload>
					</ee:message>
				</ee:transform>
			</when>
			<when expression='#[vars.Country == "Japan"]'>
				<ee:transform doc:name="response  payload" doc:id="d7290bae-15b2-4ff4-a424-3eec23e64d06" >
					<ee:message >
						<ee:set-payload ><![CDATA[%dw 2.0
output application/json
---
payload.capital[0] joinBy  ""]]></ee:set-payload>
					</ee:message>
				</ee:transform>
			</when>
			<otherwise >
				<logger level="INFO" doc:name="Invalid Country" doc:id="2e1170d4-645a-4fc5-a861-271766e9f856" message="Invalid_country_name"/>
			</otherwise>
		</choice>
		<ee:transform doc:name="Transform Message" doc:id="4175d2f6-1cb1-4557-8553-ff93a2a4a06e">
					<ee:message>
						<ee:set-payload><![CDATA[%dw 2.0
output application/json
---
payload]]></ee:set-payload>
					</ee:message>
				</ee:transform>
		<scatter-gather doc:name="Scatter-Gather" doc:id="51372c7f-5200-45e4-8e85-ee16bf2c4152" >
			<route >
				<email:send doc:id="113e8940-f2f6-42a6-9c59-707a94236fb9" config-ref="Email_SMTP" fromAddress="vignesh.mohan@mulecraft.in" subject="country_capital" doc:name="Sending country_capitals" toAddresses="vigneshvnb12@gmail.com"/>
			</route>
			<route >
				<db:insert doc:id="a07ee668-af04-4a58-a12c-5a9f3bbf5c44" config-ref="Database_Config" doc:name="country_capital inserted">
			<db:sql><![CDATA[INSERT INTO country_capital
(country,captial)
VALUES(:country, :captial);]]></db:sql>
			<db:input-parameters><![CDATA[#[{
	'country': vars.Country,
	'capital':payload,
}]]]></db:input-parameters>
		</db:insert>
			</route>
		</scatter-gather>
		<logger level="INFO" doc:name="End Logger" doc:id="e204de0f-dbab-4a06-b129-1475063cb62f" message="Flow Ended successfully ++ #[payload]"/>
	</flow>
</mule>
Example for Flow Control in Mule 4

Execution behavior for the previous example is as follows:

Scheduler: Schedules the flow to run at fixed intervals (every 2 minutes in this case).

Round-robin: A round-robin router that sets the variable "Country" alternatively to "India" and "Japan".

HTTPS:request: Sends an HTTP GET request to "restcountries.com" with the country name dynamically set from the variable.

Choice: A conditional router based on the value of the "Country" variable. Inside the choice, two when conditions to handle "India" and "Japan" cases, each transforming the response payload to extract the capital. An otherwise condition that logs an info message for an invalid country name.

Transform: Transforms the message payload (capital) into JSON format.

Scatter-gather: Sends the transformed payload to two routes.

Sends an email with the country capital information.
Inserts the country capital information into a database using a PostgreSQL insert query statement.

Database Configuration & Insert Operation

The db: insert component inserts data into the database table named country_capital with columns country and capital. Replace the fields with valid values concerning your database and mail provider.

Email Sending

Email send component sends an email to the given mail address with the country capital information.

The flow essentially fetches information about the capitals of two countries ("India" and "Japan") from an external API, processes the response, and then sends the information via email and stores it in a database. The flow is scheduled to run every 2 minutes.

Conclusion

These flow control connectors provide developers with powerful tools to design flexible, efficient, and robust integration solutions in Mule 4 by allowing them to manage the execution flow based on different conditions, iterate over collections, and handle data in parallel. They contribute to building scalable and responsive integrations in MuleSoft.

Mulecraft Footer