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
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

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • Providing Enum Consistency Between Application and Data
  • Performance Engineering Management: A Quick Guide
  • Moving PeopleSoft ERP Data Between Databases With Data Mover Scripts
  • Understanding Multi-Leader Replication for Distributed Data

Trending

  • Reducing Hallucinations Using Prompt Engineering and RAG
  • MCP and The Spin-Off CoT Pattern: How AI Agents Really Use Tools
  • Lessons Learned in Test-Driven Development
  • Advancing DSLs in the Age of GenAI
  1. DZone
  2. Data Engineering
  3. Data
  4. Mule Caching on Application Boot Up and Mule Registry

Mule Caching on Application Boot Up and Mule Registry

This tutorial explains how to retrieve master data from database and store it while the Mule application starts up.

By 
Vishnu Ramakrishnan user avatar
Vishnu Ramakrishnan
·
Jun. 25, 18 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
10.1K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, we will learn how to retrieve look-up/Master data from database and store/cache it while Mule application starts/boots up. Also, we will learn how to use Mule Registry.

What Are We Doing?

In this example, we are caching simple lookup table data as key/value pair in Java HashMap upon Mule interface boot up and store the HashMap result in Mule Registry that can be accessed from Mule Flow.

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import org.mule.api.MuleContext;
import org.mule.api.context.MuleContextAware;

import org.mule.api.context.notification.MuleContextNotificationListener;
import org.mule.context.notification.MuleContextNotification;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class CacheUtil implements MuleContextNotificationListener<MuleContextNotification>, MuleContextAware {

    public static HashMap<String, String> supplierMappingMap;
    private MuleContext muleContext;

    @Value("${sql.database.uri}")
    private String sqlBaseURL;

    @Value("${sql.select.statement}")
    private String sqlSupplierSelectStatement;


    public void setMuleContext(MuleContext context) {
        this.muleContext = context;
    }

    public void onNotification(MuleContextNotification notification) {

        LOGGER.info("Executing CacheUtil onNotification()");
        if (notification.getAction() == MuleContextNotification.CONTEXT_STARTING) {

            try {
                getSupplierID();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

   public HashMap<String, String> getSupplierID() throws Exception {

        String selectSupplierID = sqlSupplierSelectStatement;
        Connection connection = null;
        PreparedStatement prepStatement = null;
        ResultSet resultSet = null;

        try {

            connection = FinUtil.getDBConnection(sqlBaseURL);
            prepStatement = connection.prepareStatement(selectSupplierID);
            resultSet = prepStatement.executeQuery();
            supplierMappingMap = new HashMap<String, String>();

            while (resultSet.next()) {
                supplierMappingMap.put(resultSet.getString(ResourceConstants.ABC_SUPP_ID),
                        resultSet.getString(ResourceConstants.XYZ_SUPP_ID));
            }

/*
If you want to test it quickly, use below hard-coded values.

        supplierMappingMap.put("abc", "012");
        supplierMappingMap.put("ijk", "456");
        supplierMappingMap.put("xyz", "890");
*/

muleContext.getRegistry().registerObject("supplierMappingMap", supplierMappingMap);  

// We can access the Mule registry by
//System.out.println("Mule Registry: " + muleContext.getRegistry().get("supplierMappingMap")); 

        } catch (Exception exception) {
            LOGGER.error("Exception in CacheUtil getSupplierID(): " + exception.getMessage());
        } finally {
resultSet.close();
prepStatement.close();
connection.close();
}
return supplierMappingMap;
    }
}

MuleContextNotificationListener is an observer interface that objects can implement and then register themselves with the Mule manager to be notified when a Manager event occurs. MuleContextNotification is fired when an event such as the mule context start occurs. The payload of this event will always be a reference to the muleContext.

(notification.getAction() == MuleContextNotification.CONTEXT_STARTING)

As we can see, HashMap is defined as static, meaning it is a class level variable (NOT object level) and gets memory only once at the time of class loading. So, when we fetch the values from database and store it in HashMap, the values are retained and can be reused several times. This is memory efficient way of caching the data.

This HashMap can be accessed from other Beans/Java classes by,

HashMap<String, String> supplierMap = CacheUtil.supplierMappingMap;

The reason I am returning the HashMap with the result from DB in getSupplierID() method is to show different ways of accessing app registry in Mule flow.

Now let’s see how we can access this map from Mule flows.

This line of code will store the map object in MuleContext registry, which can be accessed in Mule flows.

 muleContext.getRegistry().registerObject("supplierMappingMap", supplierMappingMap); 

There are multiple ways of accessing the registry data in Mule flows. Please refer to the mule code.

#[app.registry.get('supplierMappingMap').get('abc')];

#[app.registry.get('CacheUtil').supplierMappingMap];

#[app.registry['CacheUtil'].getSupplierID();]

Here is a wonderful article about inner workings of Mule including Registry.

How to Access Newly Added Rows/Data in the Lookup Table

As we can observe from the code, we have used Spring annotation @Component to mark the CacheUtil as a bean. Hence, we can use @Autowired to inject CacheUtil bean from another bean/Java class to invoke getSupplierID() method, so it reloads the rows/data from database table as needed.

@Autowired

private CacheUtil cacheUtil;

cacheUtil.getSupplierOracleID();

@Value annotation:

The easiest way to access properties(key/value pair) from Java layer using spring is through @Value annotation.

Mule Flow:

    <spring:beans>
        <spring:bean id="CacheUtil" name="CacheUtil" class="muleregistry.CacheUtil" />
    </spring:beans> 

    <flow name="muleregistryFlow">
        <poll doc:name="Poll">
            <fixed-frequency-scheduler frequency="10000"/>
            <logger level="INFO" doc:name="Logger" message="Flow Started"/>
        </poll>

        <logger message="Key (abc): #[app.registry.get('supplierMappingMap').get('abc')];" level="INFO" doc:name="Logger"/>
        <logger message="Key (xyz): #[app.registry.get('supplierMappingMap').get('xyz')];" level="INFO" doc:name="Logger"/>
        <logger message="#[app.registry.get('CacheUtil').supplierMappingMap];" level="INFO" doc:name="Logger"/>
    <logger message="Method: #[app.registry['CacheUtil'].getSupplierID();]" level="INFO" doc:name="Logger"/>
    </flow>

Without spring bean definition in XML configuration, we get java.lang.NullPointerException

Output:

 muleRegistry * default * DEPLOYED *

INFO 2018-06-22 18:55:23,662 [pool-14-thread-1] org.mule.api.processor.LoggerMessageProcessor: Flow Started

INFO 2018-06-22 18:55:23,664 [[muleregistryone].muleregistryoneFlow.stage1.02] org.mule.api.processor.LoggerMessageProcessor: Key (abc): 012;

INFO 2018-06-22 18:55:23,664 [[muleregistryone].muleregistryoneFlow.stage1.02] org.mule.api.processor.LoggerMessageProcessor: Key (xyz): 890;

INFO 2018-06-22 18:55:23,665 [[muleregistryone].muleregistryoneFlow.stage1.02] org.mule.api.processor.LoggerMessageProcessor: Field: {, , };

WARN 2018-06-22 18:55:23,665 [[muleregistryone].muleregistryoneFlow.stage1.02] org.mule.config.spring.SpringRegistry: Spring registry already contains an object named 'supplierMappingMap'. The previous object will be overwritten.

INFO 2018-06-22 18:55:23,666 [[muleregistryone].muleregistryoneFlow.stage1.02] org.mule.api.processor.LoggerMessageProcessor: Method: {, , }

Conclusion:

Though Mule registry is not recommended for general purpose data cache, in this scenario, we are storing only less 100 rows of lookup data, which is static in nature. If you have to cache a large volume of data, please use Mule cache scope.

Cache (computing) application Database

Opinions expressed by DZone contributors are their own.

Related

  • Providing Enum Consistency Between Application and Data
  • Performance Engineering Management: A Quick Guide
  • Moving PeopleSoft ERP Data Between Databases With Data Mover Scripts
  • Understanding Multi-Leader Replication for Distributed Data

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: