How to use map states in routes

Learn how to map states in routes.

Prerequisite: How to configure states

Keep a state between successive from triggers and successive runs

Consider that you have a map state named indexes.

You can use the following route:

<?xml version="1.0" encoding="UTF-8"?>
<routes xmlns="http://camel.apache.org/schema/spring" xmlns:u="http://www.systar.com/aluminium/camel-util">
    <route>
        <from uri="timer:tick?period=5s"/>
        
        <!-- Get the state-->
        <setHeader headerName="state">
            <groovy>
                def state = camelContext.registry.lookupByName('indexes').getState('process-1')
                state != null ? state as int : 0
            </groovy>
        </setHeader>
        
        <!-- Execute with the state -->
        <to uri="direct:execute"/>
        
        <!-- Save the state -->
        <setHeader headerName="state">
            <groovy>
                camelContext.registry.lookupByName('indexes').setState('process-1', request.headers['state'] as String)
            </groovy>
        </setHeader>
    </route>
    
    <route>
        <from uri="direct:execute"/>
        
        <!-- Some process with a state -->
        <log message="State = ${header.state}"/>
        
        <!-- Then update the state -->
        <setHeader headerName="state">
            <groovy>request.headers['state'] + 1</groovy>
        </setHeader>
    </route>
</routes>

Notes:

  • As the indexes are stored in a map, you need a key to access it. In this example, we're using process-1 but it can be any String.
  • The state is persisted as String so you must convert it back and forth to the type you need (int in the example).
  • The content of the state is stored in the deployment storage; restarting from a checkpoint will restore the indexes to their values at the checkpoint creation moment.

Related Links