You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by GitBox <gi...@apache.org> on 2021/02/04 11:11:06 UTC

[GitHub] [camel-k] lancerdima edited a comment on issue #1984: Options to share state between routes

lancerdima edited a comment on issue #1984:
URL: https://github.com/apache/camel-k/issues/1984#issuecomment-773227390


   Leaving the snippets below with a solution to the shared state problem, as a contribution to the community. 
   Valid for Camel K 1.3 runtime.
   
   In this case:
   * primary route retrieves event from Salesforce (can be any) and captures the offset of the topic
   * secondary route, every 10 seconds does something useful with the offset
   
   YAML integration definition
   ```
   - from:
       uri: "salesforce:event/PlatformEvent__e"
       steps:
         - {some useful stuff}
         - {some more useful stuff}
         - to: bean:cache?method=set("offset", ${headers.CamelSalesforceReplayId})  # Capture the offset
   - from:
       uri: "timer:offsetHandler?fixedRate=true&period=10000&delay=10000"
       steps:
         - to: bean:cache?method=get("offset")    # Retrieve the offset from cache
         - log: "Offset Store: ${body}"
   - beans:
       - name: cache
         type: mycache.InMemoryKeyValueStore
   ```
   
   Bean to capture state
   ```
   package mycache;
   
   import org.apache.camel.Handler;
   import org.apache.camel.builder.RouteBuilder;
   
   import java.util.Map;
   import java.util.concurrent.ConcurrentHashMap;
   
   public class InMemoryKeyValueStore extends RouteBuilder {
   	@Override
   	public void configure() throws Exception {
   	}
   
       private Map<String, Object> container;
   
       private Map<String, Object> getContainer() {
           if (this.container == null) {
               this.container = new ConcurrentHashMap<>();
           }
           return this.container;
       }
   
       @Handler
       public Object get(String key) {
           Map<String, Object> container = this.getContainer();
   
           if (container.containsKey(key)) {
               return container.get(key);
           }
   
           return null;
       }
   
       @Handler
       public void remove(String key) {
           Map<String, Object> container = this.getContainer();
   
           if (container.containsKey(key)) {
               container.remove(key);
           }
       }
   
       @Handler
       public void set(String key, Object value) {
           Map<String, Object> container = this.getContainer();
           container.put(key, value);
       }
   }
   ```


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
users@infra.apache.org