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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Providing Enum Consistency Between Application and Data
  • Performance Engineering Management: A Quick Guide
  • The Bill You Didn't See Coming
  • Moving PeopleSoft ERP Data Between Databases With Data Mover Scripts

Trending

  • How Performance Engineers Find and Fix Hidden System Bottlenecks
  • 5 Proven Strategies for Modernizing Legacy .NET Applications
  • Agentic Test Creation: From Plain-Language Requirements to End-to-End Test Cases
  • Giving AI Agents Safe Access to Legacy Systems: Introducing legacy2mcp

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Jun. 25, 18 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
10.4K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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
  • The Bill You Didn't See Coming
  • Moving PeopleSoft ERP Data Between Databases With Data Mover Scripts

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook