Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Implementing Shared Variables in Mule

DZone's Guide to

Implementing Shared Variables in Mule

Want to share your data across a project? See how you can create and implement shared variables in Mule to do just that using singleton Java POJOs.

· Integration Zone ·
Free Resource

SnapLogic is the leading self-service enterprise-grade integration platform. Download the 2018 GartnerMagic Quadrant for Enterprise iPaaS or play around on the platform, risk free, for 30 days.

Ever wondered why session variables can't be shared across JMS transports?

I was trying to receive messages from a JMS Queue and, in case of an error, increment a counter until a threshold limit is reached. 

I tried setting a session variable in case of an exception and then incrementing it with:

<set-session-variable variableName="errorCounter" value="#[((sessionVars['errorCounter'] == null) ? 0 : sessionVars['errorCounter']) + new Integer(1).intValue()]"doc:name="Error Counter"/>


But as soon as the next thread of JMS Receiver starts, the session variable value is lost — it's null again.

The Workaround

  1. Create a POJO Java class with all the values we want to get and set in our Mule flows lying in the same project.

  2. Let's create a ErrorCounter.java class under src/main/java under the org.mule.utils package.

  3. package org.mule.utils;
    public class ErrorCounter {
    
        int errorCounter = 0;
           
        public int increment()
        {
            errorCounter++;
            return errorCounter;
        }
    }


    We can create getters and setters here, as we do in a JAVA POJO, and modify those functions as per our requirements.

  4. Next, create a singleton spring-bean instantiating the above class in your mule-config xml file.

    <spring:beans>
        <spring:bean id="ErrorCounter" name="ErrorCounter"scope="singleton" class="org.mule.utils.ErrorCounter"/>
    </spring:beans>

  5. Access these variables in mule flows using expressions to get and set the values. In this case, I am storing the value into a flow variable, which will have the value incremented when the next JMS Message is received.

    <set-variable variableName="errorCounter" value="#[app.registry['ErrorCounter'].increment();]" doc:name="Increment-Counter"/>


Hope this Helps. Thanks for reading!

With SnapLogic’s integration platform you can save millions of dollars, increase integrator productivity by 5X, and reduce integration time to value by 90%. Sign up for our risk-free 30-day trial!

Topics:
mulesoft

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}