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

Modernize your application architectures with microservices and APIs with best practices from this free virtual summit series. Brought to you in partnership with CA Technologies.

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!

The Integration Zone is proudly sponsored by CA Technologies. Learn from expert microservices and API presentations at the Modernizing Application Architectures Virtual Summit Series.

Topics:
mulesoft

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}