Dynamic Router
Since Camel 3.15
Only producer is supported
The Dynamic Router Component is an implementation of the Dynamic Router EIP. Participants may send subscription messages over a special control channel, at runtime, to specify the conditions under which messages are routed to their endpoint (also provided in the control channel message). In this way, the Dynamic Router is an extension of the content-based router EIP. When a recipient wishes to remove itself, it can also send a message to unsubscribe.
Note that, while Camel Core contains an implementation of the Dynamic Router EIP, this component is a completely separate implementation that aims to be a closer reflection of the EIP description. The main differences between the Core implementation and this component implementation are as follows:
- Control Channel
-
A reserved communication channel by which routing participants can subscribe or unsubscribe to receiving messages that meet their criteria.
-
core: does not have a communication channel for control messages. Perhaps the "re-circulation" behavior, discussed below, is the core Dynamic Router’s control channel interpretation.
-
component: provides a control channel for participants to subscribe and unsubscribe with control messages that contain a
Predicateto determineExchangesuitability, and theEndpointURI that a matchingExchangewill be sent to.
-
- Dynamic Rule Base
-
The Dynamic Router should have a list of routing recipients' criteria that define the terms under which an exchange is suitable for them to receive.
-
core: implements a dynamic version of a
Routing Slipfor this purpose, but that is not inherently dynamic in terms of its content. If the content of this slip is dynamic, it will be up to the user to define and implement that capability. -
component: builds the rule base at runtime, and maintains it as participants subscribe or unsubscribe via the control channel.
-
- Message Re-Circulation
-
The Dynamic Router EIP description does not specify any message re-circulation behavior.
-
core: provides a feature that continuously routes the exchange to a recipient, then back through the dynamic router, until a recipient returns
nullto signify routing termination. This may be an interpretation of the control channel feature. -
component: does not provide a re-circulation feature. If this is the desired behavior, the user will have to define and implement this behavior. E.g., create a simple route to send a response back through the Dynamic Router under some condition(s).
-
For some use cases, the core Dynamic Router will be more appropriate. In other cases, the Dynamic Router Component will be a better fit.
URI format
dynamic-router:channel[?options]
The channel is the routing channel that allows messaging to be logically separate from other channels. Any string that can be included in a URI is a valid channel name. Each channel can have a set of participant subscriptions, and can consume messages to be routed to appropriate recipients. The only reserved channel is the control channel. This is a single channel that handles control messages for participants to subscribe or unsubscribe for messaging over a desired channel.
These messages will be described in greater detail below, with examples.
Configuring Options
Camel components are configured on two separate levels:
-
component level
-
endpoint level
Configuring Component Options
At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.
For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.
Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.
You can configure components using:
-
the Component DSL.
-
in a configuration file (
application.properties,*.yamlfiles, etc). -
directly in the Java code.
Configuring Endpoint Options
You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.
Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.
A good practice when configuring options is to use Property Placeholders.
Property placeholders provide a few benefits:
-
They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.
-
They allow externalizing the configuration from the code.
-
They help the code to become more flexible and reusable.
The following two sections list all the options, firstly for the component followed by the endpoint.
Component Options
The Dynamic Router component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean |
Endpoint Options
The Dynamic Router endpoint is configured using URI syntax:
dynamic-router:channel
With the following path and query parameters:
Path Parameters
| Name | Description | Default | Type |
|---|---|---|---|
The name of the channel. An exchange sent to this endpoint goes to the subscriptions made on this channel (the subscribeChannel of the dynamic-router-control endpoint), and channels keep their subscriptions apart. Only one endpoint URI per channel can be in use at a time, so that URI sets the options of the channel. | String |
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
The name of the bean in the registry that combines the replies of the recipients into the outgoing message: an AggregationStrategy, a BiFunction that takes the old and the new exchange, or a POJO with an aggregate method (see aggregationStrategyMethodName). By default the reply of the last recipient is used. | String | ||
The AggregationStrategy that combines the replies of the recipients into the outgoing message, instead of aggregationStrategy. By default the reply of the last recipient is used. | AggregationStrategy | ||
Whether the aggregate method of a POJO or BiFunction aggregationStrategy is also called when the old exchange (for the first reply) or the new exchange is null. When disabled, the other exchange is used as the result without calling the method. | false | boolean | |
The name of the method that aggregates the replies, when the aggregationStrategy bean is a POJO. When not set, Camel selects the method. | String | ||
The maximum number of producers to cache and reuse for the destination URIs of the subscriptions. Use 0 for the default maximum cache size of the CamelContext, or -1 to turn the cache off. | 100 | int | |
The thread pool for parallelProcessing: the name of an ExecutorService bean in the registry, or else the ID of a thread pool profile to create one from. It is only used when parallelProcessing is enabled. By default a thread pool of the default thread pool profile is created. | String | ||
The ExecutorService to use as the thread pool for parallelProcessing, instead of executorService. It is only used when parallelProcessing is enabled. | ExecutorService | ||
Whether to skip a recipient whose destination URI cannot be resolved to an endpoint, such as one with an unknown component scheme, instead of failing the exchange. | false | boolean | |
The name of a Processor bean in the registry to call with the copy of the exchange for each recipient before it is sent, for example to deep-clone the message body. | String | ||
A Processor to call with the copy of the exchange for each recipient before it is sent. The Dynamic Router currently ignores this option: set onPrepare to the name of a Processor bean instead. | Processor | ||
Whether the aggregate method of the AggregationStrategy may be called concurrently for several replies, which requires a thread-safe AggregationStrategy. By default Camel calls it for one reply at a time. | false | boolean | |
Whether to send the exchange to the recipients concurrently, in a thread pool (see executorService). The route continues when all recipients are done, on the thread of the last reply unless synchronous is enabled. Only matters with recipientMode allMatch, where an exchange can have several recipients. | false | boolean | |
How many subscriptions receive an exchange. firstMatch sends it to the first subscription whose predicate matches, evaluating the subscriptions in order of priority (the lowest number first). allMatch sends it to every subscription whose predicate matches, in order of priority. Enum values:
| firstMatch | String | |
Whether the copies of the exchange sent to the recipients share the unit of work of the original exchange. By default each copy has its own unit of work. | false | boolean | |
Whether to stop sending the exchange to further recipients as soon as a recipient fails, also when the error handler handled the exception (such as with onException), and fail the exchange with that exception. By default all recipients get the exchange. | false | boolean | |
Whether to aggregate the replies in the order they come back, instead of the order of the recipients. Only has an effect with parallelProcessing. | false | boolean | |
Whether to process the exchange synchronously: the calling thread waits until all recipients have processed the exchange and then continues the route, also with parallelProcessing enabled. | false | boolean | |
The total time in milliseconds to wait for the replies of all recipients, which requires parallelProcessing (otherwise the endpoint fails to start). When it expires, the Dynamic Router calls the timeout method of the AggregationStrategy and continues with the replies aggregated so far, while the recipients that are still running are not stopped. 0 or less means no timeout. | -1 | long | |
Whether to log at WARN level, instead of DEBUG, when no subscription on the channel matches an exchange. Such an exchange goes to a log endpoint, with its body replaced by a text that says so and the original body in the originalBody header. | false | boolean | |
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
Sets an optional comma-separated allow-list of component schemes that a subscription destination may resolve to (e.g. http,https). When set, a subscription whose destination URI uses a scheme that is not in the list is rejected. By default (unset) any scheme is allowed. | String |
Message Body
The message body at each side of the Dynamic Router component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.
| Side | Body | Description |
|---|---|---|
Producer input |
| The message to route: the predicates of the subscriptions on the channel decide where it goes. |
Producer output |
| The body the recipient ends with; with allMatch, the one of the last recipient unless an aggregationStrategy is set. When no subscription matches, a text that says so, with the body in the originalBody header. |
The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.
Usage
Maven users will need to add the following dependency to their pom.xml for this component:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-dynamic-router</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency> Gradle users will need to add the following dependency to their build.gradle for this component:
implementation group: 'org.apache.camel', name: 'camel-dynamic-router', version: 'x.x.x'
// use the same version as your Camel core version The Dynamic Router component is used in the same way that other components are used. Include the dynamic-router URI as a consumer in a route, along with the channel name.
-
Java
-
XML
-
YAML
// Send a message to the Dynamic Router channel named "orders"
from("direct:start").to("dynamic-router:orders"); <route>
<from uri="direct:start"/>
<to uri="dynamic-router:orders"/>
</route> - route:
from:
uri: direct:start
steps:
- to:
uri: dynamic-router:orders Examples
The benefit of the Dynamic Router EIP Component can best be seen, perhaps, through looking at some use cases. These examples are not the only possibilities with this component, but they show the basics of two main usages — message routing within a single JVM, and message routing across multiple JVMs.
Dynamic Router within a single JVM or Application
The Dynamic Router EIP component can receive messages from a single source and dispatch them to interested recipients. If we have a simple point-of-sale application, we might have services that:
-
Process orders
-
Adjust inventory counts
-
Process returns
For the purpose of this example, the exact steps that each service carries out are not as important as the fact that each service needs to be notified that it needs to do something under the right condition(s). So, each service will subscribe to participate in routing:
DynamicRouterControlMessage controlMessage = DynamicRouterControlMessage.newBuilder()
.subscribeChannel("orders")
.subscriptionId("orderProcessing")
.destinationUri("direct:orders")
.priority(5)
.predicate("${header.command} == 'processOrder'")
.expressionLanguage("simple")
.build();
producerTemplate.sendBody("dynamic-router-control:subscribe?allowPredicateFromMessage=true", controlMessage); DynamicRouterControlMessage controlMessage = DynamicRouterControlMessage.newBuilder()
.subscribeChannel("orders")
.subscriptionId("inventoryProcessing")
.destinationUri("direct:orders")
.priority(5)
.predicate("${header.command} == 'processOrder' || ${header.command} == 'processReturn'")
.expressionLanguage("simple")
.build();
producerTemplate.sendBody("dynamic-router-control:subscribe?allowPredicateFromMessage=true", controlMessage); DynamicRouterControlMessage controlMessage = DynamicRouterControlMessage.newBuilder()
.subscribeChannel("orders")
.subscriptionId("returnsProcessing")
.destinationUri("direct:orders")
.priority(5)
.predicate("${header.command} == 'processReturn'")
.expressionLanguage("simple")
.build();
producerTemplate.sendBody("dynamic-router-control:subscribe?allowPredicateFromMessage=true", controlMessage); Above, we have the Orders service subscribing for all messages where the command header is "processOrder", and the Returns service subscribing for all messages where the command header is "processReturn". The Inventory service is interested in both types of messages, since it must deduct from the inventory when an order request comes through, and it must add to inventory counts when a return request comes through. So, for either type of message, two services will be notified.
The order messages get sent to the dynamic router:
-
Java
-
XML
-
YAML
from("direct:start")
.process(myOrderProcessor)
.to("dynamic-router:orders?recipientMode=allMatch"); <route>
<from uri="direct:start"/>
<to uri="bean:myOrderProcessor"/>
<to uri="dynamic-router:orders?recipientMode=allMatch"/>
</route> - route:
from:
uri: direct:start
steps:
- to:
uri: bean:myOrderProcessor
- to:
uri: dynamic-router:orders
parameters:
recipientMode: allMatch Note the .process(myOrderProcessor) step. If incoming messages need to be validated, enriched, transformed, or otherwise augmented, that can be done before the Dynamic Router receives the message. Then, when the Dynamic Router receives a message, it checks the Exchange against all subscriptions for the orders channel to determine if it is suitable for any of the recipients. Orders should have a header (command → processOrder), so the message will be routed to the orders service, and the inventory service. The system will process the order details, and then the inventory service will deduct from merchandize counts. Likewise, returns should have a header (command → processReturn), so the message will be routed to the returns service, where the return details will be processed, and the inventory service will increase the relevant merchandise counts.
Dynamic Router across multiple JVMs or Applications
The Dynamic Router EIP component is particularly well-suited to serve as the primary orchestration mechanism between various applications and services that comprise an application stack. Note that the Dynamic Router cannot achieve this by itself, and that some other transport is required to allow messages to pass between services that exist in separate JVMs. For example, a message transport implementation like Kafka, Artemis, or Protocol Buffers, could be used.
Let’s look at the point-of-sale example in a different context. In a microservice architecture, this system would have several separate application modules, with the orders service, inventory service, and returns service, contained within their own microservice (application). Similar to the single-JVM example, all services will subscribe, but they will need to send their subscriptions through a transport that can communicate to another JVM. Their subscriptions might look like:
DynamicRouterControlMessage controlMessage = DynamicRouterControlMessage.newBuilder()
.subscribeChannel("orders")
.subscriptionId("orderProcessing")
.destinationUri("direct:orders")
.priority(5)
.predicate("${header.command} == 'processOrder'")
.expressionLanguage("simple")
.build();
ObjectMapper mapper = new ObjectMapper(new JsonFactory());
producerTemplate.sendBody("kafka://subscriptions", mapper.writeValueAsString(controlMessage)); DynamicRouterControlMessage controlMessage = DynamicRouterControlMessage.newBuilder()
.subscribeChannel("orders")
.subscriptionId("inventoryProcessing")
.destinationUri("direct:orders")
.priority(5)
.predicate("${header.command} == 'processOrder' || ${header.command} == 'processReturn'")
.expressionLanguage("simple")
.build();
ObjectMapper mapper = new ObjectMapper(new JsonFactory());
producerTemplate.sendBody("kafka://subscriptions", mapper.writeValueAsString(controlMessage)); DynamicRouterControlMessage controlMessage = DynamicRouterControlMessage.newBuilder()
.subscribeChannel("orders")
.subscriptionId("returnsProcessing")
.destinationUri("direct:orders")
.priority(5)
.predicate("${header.command} == 'processReturn'")
.expressionLanguage("simple")
.build();
ObjectMapper mapper = new ObjectMapper(new JsonFactory());
producerTemplate.sendBody("kafka://subscriptions", mapper.writeValueAsString(controlMessage)); In another module, additional routing will serve as a bridge to get the message from Kafka to the control channel of the Dynamic Router. The subscriptions above carry their predicate in the control message, so the bridge has to opt in with allowPredicateFromMessage=true.
|
|
-
Java
-
XML
-
YAML
from("kafka:subscriptions")
.unmarshal().json(DynamicRouterControlMessage.class)
.to("dynamic-router-control:subscribe?allowPredicateFromMessage=true"); <route>
<from uri="kafka:subscriptions"/>
<unmarshal>
<json library="Jackson" unmarshalType="org.apache.camel.component.dynamicrouter.control.DynamicRouterControlMessage"/>
</unmarshal>
<to uri="dynamic-router-control:subscribe?allowPredicateFromMessage=true"/>
</route> - route:
from:
uri: kafka:subscriptions
steps:
- unmarshal:
json:
library: Jackson
unmarshalType: org.apache.camel.component.dynamicrouter.control.DynamicRouterControlMessage
- to:
uri: dynamic-router-control:subscribe
parameters:
allowPredicateFromMessage: true Order requests or return requests might also arrive via Kafka. The route is essentially the same as the route in the single-JVM example. Instead of forwarding the incoming message, as-is, from the "direct" component to the router, the messages are deserialized from a String, and converted to an instance of the "order" object. Then, it can be sent to the Dynamic Router for evaluation and distribution to the appropriate subscribing recipients:
-
Java
-
XML
-
YAML
from("kafka://orders")
.unmarshal().json(MyOrderMessage.class)
.process(myOrderProcessor)
.to("dynamic-router:orders?recipientMode=allMatch"); <route>
<from uri="kafka://orders"/>
<unmarshal>
<json library="Jackson" unmarshalType="com.example.MyOrderMessage"/>
</unmarshal>
<to uri="bean:myOrderProcessor"/>
<to uri="dynamic-router:orders?recipientMode=allMatch"/>
</route> - route:
from:
uri: kafka://orders
steps:
- unmarshal:
json:
library: Jackson
unmarshalType: com.example.MyOrderMessage
- to:
uri: bean:myOrderProcessor
- to:
uri: dynamic-router:orders
parameters:
recipientMode: allMatch Note the .process(myOrderProcessor) step. If incoming messages need to be validated, enriched, transformed, or otherwise augmented, that can be done before the Dynamic Router receives the message. Then, when the Dynamic Router receives a message, it checks the Exchange against all subscriptions for the "orders" channel to determine if it is suitable for any of the recipients. Orders should have a header (command → processOrder), so the message will be routed to the orders service, and the inventory service. The system will process the order details, and then the inventory service will deduct from merchandise counts. Likewise, returns should have a header (command → processReturn), so the message will be routed to the returns service, where the return details will be processed, and the inventory service will increase the relevant merchandise counts.
Further learning: a complete Spring Boot example
In the camel-spring-boot-examples project, the dynamic-router-eip-multimodule module serves as a complete example in this category that you can run and/or experiment with to get a practical feel for how you might use this in your own multi-JVM application stack.
JMX Control and Monitoring Operations
The Dynamic Router Control component supports some JMX operations that allow you to control and monitor the component. It is beyond the scope of this document to go into detail about JMX, so this is a list of the operations that are supported. For more information about JMX, see the JMX documentation.
String subscribeWithPredicateExpression(String, String, String, int, String, String, boolean) This operation provides the ability to subscribe to a channel with a predicate expression. The parameters, in order, are as follows:
-
subscription ID
-
channel name
-
destination URI
-
priority
-
predicate expression
-
expression language
-
update the subscription (true), or add a new one (false)
String subscribeWithPredicateBean(String, String, String, int, String, boolean) This operation provides the ability to subscribe to a channel with the name of a Predicate that has been bound in the registry. The parameters, in order, are as follows:
-
subscription ID
-
channel name
-
destination URI
-
priority
-
predicate bean name
-
update the subscription (true), or add a new one (false)
String subscribeWithPredicateInstance(String, String, String, int, Object, boolean) This operation provides the ability to subscribe to a channel with an instance of a Predicate. The parameters, in order, are as follows:
-
subscription ID
-
channel name
-
destination URI
-
priority
-
predicate instance
-
update the subscription (true), or add a new one (false)
boolean removeSubscription(String, String) This operation provides the ability to unsubscribe from a channel. The parameters, in order, are as follows:
-
subscription ID
-
channel name
Map<String, ConcurrentSkipListSet<PrioritizedFilter>> getSubscriptionsMap() This operation provides the ability to get the subscriptions map. The map is keyed by channel name, and the values are a set of prioritized filters.
Map<String, List<PrioritizedFilterStatistics>> getSubscriptionsStatisticsMap() This operation provides the ability to get the subscriptions statistics map. The map is keyed by channel name, and the values are a list of prioritized filter statistics, including the number of messages that have matched the filter, and had the exchange sent to the destination URI.