DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Enabling Business Transaction Monitoring for App Connect Enterprise
  • Data Mining in IoT: From Sensors to Insights
  • MDC Logging With MuleSoft Runtime 4.4
  • Low Code Serverless Integration With Kafka

Trending

  • Send Your Logs to Loki
  • Wild West to the Agile Manifesto [Video]
  • Spring Authentication With MetaMask
  • API Design
  1. DZone
  2. Data Engineering
  3. Databases
  4. Large Dataset Retrieval in Mule

Large Dataset Retrieval in Mule

Clare Cini user avatar by
Clare Cini
·
Oct. 02, 13 · Interview
Like (0)
Save
Tweet
Share
9.58K Views

Join the DZone community and get the full member experience.

Join For Free

Recently, a customer made a query on how to perform large dataset retrieval in Mule. The documentation page briefly explains how this may be achieved, however there is no working example on how to do this as far as I can tell. This blog post aims to explain in detail how large dataset retrieval works in Mule by giving an example.

The customer wanted to transfer items from one database to another by performing a batch select and then a batch insert. The ‘batch insert’ part is pretty straightforward and is done automatically by Mule when the payload is of type List. However, the batch select is mastered in a different way.

In order to retrieve all the records, we will use the Batch Manager to compute the ID ranges for the next batch of records to be retrieved. This is provided out of the box with Mule EE.

We start by defining the database which will be used throughout the example to retrieve and insert records. For simplicity’s  sake we are going to use the Derby in-memory database.

NOTE: the records should be identified by a key which is unique and in a sequential numeric order.

CREATE TABLE table1(KEY1 INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1)  NOT NULL PRIMARY KEY, KEY2 VARCHAR(255));
CREATE TABLE table2(KEY1 VARCHAR(255), KEY2 VARCHAR(255));

INSERT INTO table1(KEY2) VALUES ('TEST1');
INSERT INTO table1(KEY2) VALUES ('TEST2');
INSERT INTO table1(KEY2) VALUES ('TEST3');
INSERT INTO table1(KEY2) VALUES ('TEST4');
INSERT INTO table1(KEY2) VALUES ('TEST5');
INSERT INTO table1(KEY2) VALUES ('TEST6');
INSERT INTO table1(KEY2) VALUES ('TEST7');
INSERT INTO table1(KEY2) VALUES ('TEST8');
INSERT INTO table1(KEY2) VALUES ('TEST9');
INSERT INTO table1(KEY2) VALUES ('TEST10');

As explained before, the select query is based on the ID ranges that are computed by the Batch Manager when nextBatch() is called. This will return a map with the lower and upper ids to be selected. In our case, we are storing this map into a flow variable named ‘boundaries’.

<!-- Defining the JDBC connector and queries -->

<jdbc-ee:connector name="jdbcConnectorOne"
	dataSource-ref="Derby_Data_Source" validateConnections="true"
	doc:name="Database">
	<!-- in the query "selectSample" KEY1 is an autoincremented 
	column, whilst the map boundaries variable contains the current lowestID 
	and upperID to be proccessed (accessed in the query through ( #[flowVars.boundaries.lowerId] 
	and #[flowVars.boundaries.upperId) these values are automatically increased by the batch manager. -->

	<jdbc-ee:query key="selectSample"
		value="select KEY1,KEY2 from table1 where KEY1 between #[flowVars.boundaries.lowerId] and 
#[flowVars.boundaries.upperId] order by KEY1" />
</jdbc-ee:connector>

After configuring the database and the JDBC connector, we need to configure the Batch Manager. This consists of specifying the idStore (which is a text file), which the BatchManager uses to store the starting point for the next batch. Moreover, on the Batch Manager, we need to configure the batch size and the starting point.

<!-- Setting up the Batch Manager -->
<spring:bean id="idStore"
	class="com.mulesoft.mule.transport.jdbc.util.IdStore">
        <spring:property name="fileName" value="/tmp/large-dataset.txt" />
</spring:bean>

<spring:bean id="seqBatchManager"
	class="com.mulesoft.mule.transport.jdbc.components.BatchManager">
	<spring:property name="idStore" ref="idStore" />
	<spring:property name="batchSize" value="2" />
	<spring:property name="startingPointForNextBatch" value="0" />
</spring:bean>

In the documentation, you would find a reference to the noArgsWrapper. Its job is to invoke the nextBatch() method on the Batch Manager. However we find this very confusing and misleading, thus instead, we use a simple MEL expression which calls the nextBatch() directly.

Now we have to configure the main flow where we perform the batch select. Given that the records are retrieved in batches, the flow has to be called multiple times until all of the records are retrieved. To solve this, we created a composite source so that at the end of the flow, if we haven’t retrieved all the records, we re-trigger the same flow using the VM queue.

<composite-source doc:name="Composite Source">
	<http:inbound-endpoint address="http://localhost:8081/batch" doc:name="HTTP"/>
	<vm:inbound-endpoint path="batch" doc:name="VM"/>
</composite-source>

<flow-ref name="startBatch" doc:name="Flow Reference"/>

<logger level="ERROR" message="after component: #[payload]" doc:name="Logger"/>

<!-- Batch Select -->

<jdbc-ee:outbound-endpoint exchange-pattern="request-response"
	queryKey="selectSample" connector-ref="jdbcConnectorOne" doc:name="Database" />
<sub-flow name="startBatch" doc:name="startBatch" doc:description="When invoked a map consisting of the lowerid and the upperid will be returned from the batch manager">
	<set-variable variableName="boundaries"
	value="#[app.registry.seqBatchManager.nextBatch()]" doc:name="Variable"/>
</sub-flow>

Once the current batch is finished, we need to call competeBatch() to instruct the batch manager that we’re done from the current batch, and ready to process the next. If this is not done, the Batch Manager will still consider the previous batch as ‘processing’. Furthermore, we have to check whether we have retrieved all of the records so we can stop processing. We do this by checking the size of the payload that is returned from the JDBC outbound endpoint. If the payload size is ’0′ (no more records to be retrieved), we have to call the completeBatch() method with ‘-1′, instructing the Batch Manager that all of the batch is complete. We must also set the starting point for next batch to ’0′. This is required so that when the flow is triggered again from the HTTP inbound endpoint, the flow will start processing from the first record.

If the batch is not complete, we call the completeBatch() method (from the BatchManager class) with the current upperId. This sets the new starting point for the next batch to be processed. Finally we end the flow with a VM outbound on ‘batch’ which triggers the main flow to process the next batch of records.

<flow-ref name="saveSizeOfBatch" doc:name="Flow Reference"/>

<!-- processing here -->

<flow-ref name="completeBatch" doc:name="Flow Reference"/>

<logger level="ERROR" message="after jdbc batch select: #[payload]" doc:name="Logger"/>
<sub-flow name="saveSizeOfBatch" doc:name="saveSizeOfBatch" doc:description="Get the size of the current batch">
	<set-variable variableName="size" value="#[payload.size()]" doc:name="Variable"/>
</sub-flow>
<sub-flow name="completeBatch" doc:name="completeBatch">
    <choice doc:name="Choice">
	<when expression="flowVars.size == 0">
		<expression-component doc:name="Expression">
			app.registry.seqBatchManager.completeBatch(-1);
			app.registry.seqBatchManager.setStartingPointForNextBatch(0);
		</expression-component>
	</when>
	<otherwise>
		<expression-component doc:name="Expression">
			app.registry.seqBatchManager.completeBatch(flowVars.boundaries.upperId);
		</expression-component>
		<vm:outbound-endpoint path="batch" doc:name="VM"/>
	</otherwise>
    </choice>
</sub-flow>

A complete Mule configuration of the main flow shown here below.

<!-- Batch Select flow -->
	<flow name="BatchSelect" 
	doc:description="
	1. Get the first trigger from the http inbound endpoint
	2. Invoke the startBatch sub-flow to start the batch manager
	3. Invoke the JDBC batch select
	4. Insert the list of records (this will be automatically done as a batch insert)
	5. Set the batch size
	6. Call the completeBatch sub-flow to either stop processing or invoking the next batch by invoking the vm:inbound endpoint." 
	doc:name="BatchSelect">

		<composite-source doc:name="Composite Source">
			<http:inbound-endpoint address="http://localhost:8081/batch" doc:name="HTTP"/>
			<vm:inbound-endpoint path="batch" doc:name="VM"/>
		</composite-source>

		<flow-ref name="startBatch" doc:name="Flow Reference"/>

		<logger level="ERROR" message="after component: #[payload]" doc:name="Logger"/>

		<!-- Batch Select -->

		<jdbc-ee:outbound-endpoint exchange-pattern="request-response"
			queryKey="selectSample" connector-ref="jdbcConnectorOne" doc:name="Database" />
		
		<flow-ref name="saveSizeOfBatch" doc:name="Flow Reference"/>

		<!-- processing here -->

		<flow-ref name="completeBatch" doc:name="Flow Reference"/>

		<logger level="ERROR" message="after jdbc batch select: #[payload]" doc:name="Logger"/>

	</flow>



Database Flow (web browser)

Published at DZone with permission of Clare Cini, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Enabling Business Transaction Monitoring for App Connect Enterprise
  • Data Mining in IoT: From Sensors to Insights
  • MDC Logging With MuleSoft Runtime 4.4
  • Low Code Serverless Integration With Kafka

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: