Reactive Streams
Since Camel 2.19
Both producer and consumer are supported
The Reactive Streams component allows you to exchange messages with reactive stream processing libraries compatible with the reactive streams standard.
The component supports backpressure and has been tested using the reactive streams technology compatibility kit (TCK).
The Camel module provides a reactive-streams component that allows users to define incoming and outgoing streams within Camel routes, and a direct client API that allows using Camel endpoints directly into any external reactive framework.
Camel uses an internal implementation of the reactive streams Publisher and Subscriber, so it’s not tied to any specific framework. The following reactive frameworks have been used in the integration tests: Reactor Core 3, RxJava 2.
Maven users will need to add the following dependency to their pom.xml for this component:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-reactive-streams</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency> URI format
reactive-streams://stream?[options]
Where stream is a logical stream name used to bind Camel routes to the external stream processing systems.
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 Reactive Streams component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
The maximum number of threads of the worker thread pool of the built-in engine. It must not be lower than threadPoolMinSize. Threads above threadPoolMinSize are only started when the task queue of the pool is full. Idle threads stop after the keep alive time of the default thread pool profile (60 seconds by default). Not used when reactiveStreamsEngineConfiguration is set, when the engine is a bean of the registry, or with another engine (see serviceType). | 10 | int | |
The core number of threads of the worker thread pool of the built-in engine. With 0, the pool starts one thread when there is work, and more threads, up to threadPoolMaxSize, only when its task queue (maxQueueSize of the default thread pool profile, 1000 by default) is full. Not used when reactiveStreamsEngineConfiguration is set, when the engine is a bean of the registry, or with another engine (see serviceType). | int | ||
The name of the worker thread pool of the built-in engine, used in the names of its threads. The pool calls onNext, onError and onComplete of the external Subscribers of the streams. Not used when reactiveStreamsEngineConfiguration is set, when the engine is a bean of the registry, or with another engine (see serviceType), such as reactor or rxjava. | CamelReactiveStreamsWorker | String | |
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
The default backpressure strategy of the streams that routes publish to: what the Publisher of a stream does with the exchanges sent to it while a Subscriber has not requested them yet with request(n). BUFFER keeps all of them, OLDEST keeps only the oldest one and discards the newer ones, LATEST keeps only the newest one and discards the older one. A discarded exchange fails with ReactiveStreamsDiscardedException. An endpoint can set its own strategy. Enum values:
| BUFFER | ReactiveStreamsBackpressureStrategy | |
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 | |
The configuration of the worker thread pool of the built-in engine: its name, core and maximum number of threads. When set, the threadPoolName, threadPoolMinSize and threadPoolMaxSize options are not used. | ReactiveStreamsEngineConfiguration | ||
The name of the reactive streams engine (CamelReactiveStreamsService) to use: a CamelReactiveStreamsService or CamelReactiveStreamsServiceFactory bean with this name in the registry, or else the factory registered under this name on the classpath, such as reactor (camel-reactor) or rxjava (camel-rxjava). When not set, the only CamelReactiveStreamsService or CamelReactiveStreamsServiceFactory bean of the registry is used, or else the built-in engine (default-service). | String |
Endpoint Options
The Reactive Streams endpoint is configured using URI syntax:
reactive-streams:stream
With the following path and query parameters:
Path Parameters
| Name | Description | Default | Type |
|---|---|---|---|
The name of the stream, which routes and external code of the same CamelContext share. A producer publishes the exchanges to the Subscribers of the stream (CamelReactiveStreamsService.fromStream), and completes each exchange once every Subscriber received it, or fails it with ReactiveStreamsNoActiveSubscriptionsException when the stream has no Subscriber. A consumer routes the items that a Publisher sends to the Subscriber of the stream (CamelReactiveStreamsService.streamSubscriber). A stream has at most one producer and one consumer. | String |
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
The number of threads that route the items received from the stream. With more than one thread, the items can be routed out of order. | 1 | int | |
When the consumer requests more items from the Publisher, as a fraction (from 0 to 1) of maxInflightExchanges: once the items requested and not finished routing drop to this fraction of maxInflightExchanges or below, the consumer calls request(n) for the items missing up to maxInflightExchanges. With 0, it requests a new batch of maxInflightExchanges items only after all the items of the previous batch are routed; with 1, it requests more items each time an item is routed. Not used when backpressure is disabled (maxInflightExchanges of 0 or less). | 0.25 | double | |
Whether to route an exchange when the Publisher signals onComplete: the exchange has no body and the CamelReactiveStreamsEventType header set to onComplete. Otherwise the completion is only logged. | false | boolean | |
Whether to route an exchange when the Publisher signals onError: the exchange has the Throwable as body and the CamelReactiveStreamsEventType header set to onError. The error is logged at ERROR level in any case. | false | boolean | |
The maximum number of items that the consumer has requested from the Publisher with request(n) and not finished routing yet (the items not received yet, plus the items queued or being routed). This is the backpressure of the consumer. A value of 0 or less requests Long.MAX_VALUE items, which disables backpressure. | 128 | Integer | |
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | ExceptionHandler | ||
Sets the exchange pattern when the consumer creates an exchange. Enum values:
| ExchangePattern | ||
The backpressure strategy of the stream that the producer publishes to, instead of the one of the component: what the Publisher of the stream does with the exchanges sent to it while a Subscriber has not requested them yet with request(n). BUFFER keeps all of them, OLDEST keeps only the oldest one and discards the newer ones, LATEST keeps only the newest one and discards the older one. A discarded exchange fails with ReactiveStreamsDiscardedException. Enum values:
| ReactiveStreamsBackpressureStrategy | ||
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 |
Message Headers
The Reactive Streams component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
CamelReactiveStreamsEventType (consumer) Constant: | The Reactive Streams signal that the exchange routed by the consumer comes from: onNext (the exchange carries an item), onComplete (the end of the stream, only routed with forwardOnComplete) or onError (the error as body, only routed with forwardOnError). | String | |
CamelReactiveStreamsCallback (common) Constant: | Internal: the DispatchCallback that the producer sets on the exchange it publishes. The engine calls it once every Subscriber of the stream received the exchange (or it was discarded), which completes the exchange, and the producer then removes the header. | DispatchCallback |
Message Body
The message body at each side of the Reactive Streams 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 |
|---|---|---|
Consumer |
| The item the publisher emits, as it is (an Exchange it emits is routed as it is). With forwardOnComplete, the end of the stream comes as an exchange without a body; with forwardOnError, the error as a Throwable body. The CamelReactiveStreamsEventType header says which. |
Consumer reply |
| A caller of toStream or to() gets the exchange the route ends with, or its body converted to the type it asks for. |
Producer input |
| The exchange is handed to the subscribers of the stream as it is; a subscriber that asks for a type gets the body converted to it. |
Producer output |
|
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
The library is aimed to support all the communication modes needed by an application to interact with Camel data:
-
Get data from Camel routes (In-Only from Camel)
-
Send data to Camel routes (In-Only towards Camel)
-
Request a transformation to a Camel route (In-Out towards Camel)
-
Process data flowing from a Camel route using a reactive processing step (In-Out from Camel)
Getting data from Camel
To subscribe to data flowing from a Camel route, exchanges should be redirected to a named stream, like in the following snippet:
-
Java
-
XML
-
YAML
from("timer:clock")
.setBody().header(Exchange.TIMER_COUNTER)
.to("reactive-streams:numbers"); <route>
<from uri="timer:clock"/>
<setBody>
<header>CamelTimerCounter</header>
</setBody>
<to uri="reactive-streams:numbers"/>
</route> - route:
from:
uri: timer:clock
steps:
- setBody:
header: CamelTimerCounter
- to:
uri: reactive-streams:numbers In the example, an unbounded stream of numbers is associated to the name numbers. The stream can be accessed using the CamelReactiveStreams utility class.
CamelReactiveStreamsService API to obtain a Publisher from a named streamCamelReactiveStreamsService camel = CamelReactiveStreams.get(context);
// Getting a stream of exchanges
Publisher<Exchange> exchanges = camel.fromStream("numbers");
// Getting a stream of Integers (using Camel standard conversion system)
Publisher<Integer> numbers = camel.fromStream("numbers", Integer.class); The stream can be used easily with any reactive streams compatible library. Here is an example of how to use it with RxJava 2 (although any reactive framework can be used to process events).
Flowable consuming Camel streamFlowable.fromPublisher(numbers)
.doOnNext(System.out::println)
.subscribe(); The example prints all numbers generated by Camel into System.out.
Getting data from Camel using the direct API
For short Camel routes and for users that prefer defining the whole processing flow using functional constructs of the reactive framework (without using the Camel DSL at all), streams can also be defined using Camel URIs.
CamelReactiveStreamsService camel = CamelReactiveStreams.get(context);
// Get a stream from all the files in a directory
Publisher<String> files = camel.from("file:folder", String.class);
// Use the stream in RxJava
Flowable.fromPublisher(files)
.doOnNext(System.out::println)
.subscribe(); Sending data to Camel
When an external library needs to push events into a Camel route, the Reactive Streams endpoint must be set as consumer.
-
Java
-
XML
-
YAML
from("reactive-streams:elements")
.to("log:INFO"); <route>
<from uri="reactive-streams:elements"/>
<to uri="log:INFO"/>
</route> - route:
from:
uri: reactive-streams:elements
steps:
- to:
uri: log:INFO A handle to the elements stream can be obtained from the CamelReactiveStreams utility class.
Subscriber handle to push events into a Camel routeCamelReactiveStreamsService camel = CamelReactiveStreams.get(context);
Subscriber<String> elements = camel.streamSubscriber("elements", String.class); The subscriber can be used to push events to the Camel route that consumes from the elements stream.
Here is an example of how to use it with RxJava 2 (although any reactive framework can be used to publish events).
Flowable publishing events into a Camel subscriberFlowable.interval(1, TimeUnit.SECONDS)
.map(i -> "Item " + i)
.subscribe(elements); String items are generated every second by RxJava in the example, and they are pushed into the Camel route defined above.
Sending data to Camel using the direct API
Also in this case, the direct API can be used to obtain a Camel subscriber from an endpoint URI.
CamelReactiveStreamsService camel = CamelReactiveStreams.get(context);
// Send two strings to the "seda:queue" endpoint
Flowable.just("hello", "world")
.subscribe(camel.subscriber("seda:queue", String.class)); Request a transformation to Camel
Routes defined in some Camel DSL can be used within a reactive stream framework to perform a specific transformation. The same mechanism can be also used to e.g., send data to an http endpoint and continue.
The following snippet shows how RxJava functional code can request the task of loading and marshalling files to Camel.
CamelReactiveStreamsService camel = CamelReactiveStreams.get(context);
// Process files starting from their names
Flowable.just(new File("file1.txt"), new File("file2.txt"))
.flatMap(file -> camel.toStream("readAndMarshal", String.class))
// Camel output will be converted to String
// other steps
.subscribe(); In order this to work, a route like the following should be defined in the Camel context:
-
Java
-
XML
-
YAML
from("reactive-streams:readAndMarshal")
.marshal().base64(); <route>
<from uri="reactive-streams:readAndMarshal"/>
<marshal>
<base64/>
</marshal>
</route> - route:
from:
uri: reactive-streams:readAndMarshal
steps:
- marshal:
base64: {} Request a transformation to Camel using the direct API
An alternative approach consists of using the URI endpoints directly in the reactive flow:
to() to invoke a Camel endpoint from RxJavaCamelReactiveStreamsService camel = CamelReactiveStreams.get(context);
// Process files starting from their names
Flowable.just(new File("file1.txt"), new File("file2.txt"))
.flatMap(file -> camel.to("direct:process", String.class))
// Camel output will be converted to String
// other steps
.subscribe(); When using the to() method instead of the toStream, there is no need to define the route using reactive-streams: endpoints (although they are used under the hood).
In this case, the Camel transformation can be just:
-
Java
-
XML
-
YAML
from("direct:process")
.marshal().base64(); <route>
<from uri="direct:process"/>
<marshal>
<base64/>
</marshal>
</route> - route:
from:
uri: direct:process
steps:
- marshal:
base64: {} Process Camel data into the reactive framework
While a reactive streams Publisher allows exchanging data in a unidirectional way, Camel routes often use an in-out exchange pattern (e.g., to define REST endpoints and, in general, where a reply is needed for each request).
In these circumstances, users can add a reactive processing step to the flow, to enhance a Camel route or to define the entire transformation using the reactive framework.
For example, given the following route:
-
Java
-
XML
-
YAML
from("timer:clock")
.setBody().header(Exchange.TIMER_COUNTER)
.to("direct:reactive")
.log("Continue with Camel route... n=${body}"); <route>
<from uri="timer:clock"/>
<setBody>
<header>CamelTimerCounter</header>
</setBody>
<to uri="direct:reactive"/>
<log message="Continue with Camel route... n=${body}"/>
</route> - route:
from:
uri: timer:clock
steps:
- setBody:
header: CamelTimerCounter
- to:
uri: direct:reactive
- log:
message: "Continue with Camel route... n=${body}" A reactive processing step can be associated with the "direct:reactive" endpoint:
CamelReactiveStreamsService camel = CamelReactiveStreams.get(context);
camel.process("direct:reactive", Integer.class, items ->
Flowable.fromPublisher(items) // RxJava
.map(n -> -n)); // make every number negative Data flowing in the Camel route will be processed by the external reactive framework then continue the processing flow inside Camel.
This mechanism can also be used to define a In-Out exchange in a completely reactive way.
CamelReactiveStreamsService camel = CamelReactiveStreams.get(context);
// requires a rest-capable Camel component
camel.process("rest:get:orders", exchange ->
Flowable.fromPublisher(exchange)
.flatMap(ex -> allOrders())); // retrieve orders asynchronously See Camel examples (camel-example-reactive-streams) for details.
Advanced Topics
Controlling Backpressure (producer side)
When routing Camel exchanges to an external subscriber, backpressure is handled by an internal buffer that caches exchanges before delivering them. If the subscriber is slower than the exchange rate, the buffer may become too big. In many circumstances, this must be avoided.
Considering the following route:
-
Java
-
XML
-
YAML
from("jms:queue")
.to("reactive-streams:flow"); <route>
<from uri="jms:queue"/>
<to uri="reactive-streams:flow"/>
</route> - route:
from:
uri: jms:queue
steps:
- to:
uri: reactive-streams:flow If the JMS queue contains a high number of messages and the Subscriber associated with the flow stream is too slow, messages are dequeued from JMS and appended to the buffer, possibly causing an "out of memory" error. To avoid such problems, a ThrottlingInflightRoutePolicy can be set in the route.
ThrottlingInflightRoutePolicy to limit in-flight exchangesThrottlingInflightRoutePolicy policy = new ThrottlingInflightRoutePolicy();
policy.setMaxInflightExchanges(10);
from("jms:queue")
.routePolicy(policy)
.to("reactive-streams:flow"); The policy limits the maximum number of active exchanges (and so the maximum size of the buffer), keeping it lower than the threshold (10 in the example). When more than 10 messages are in flight, the route is suspended, waiting for the subscriber to process them.
With this mechanism, the subscriber controls the route suspension/resume automatically, through backpressure. When multiple subscribers are consuming items from the same stream, the slowest one controls the route status automatically.
In other circumstances, e.g., when using a http consumer, the route suspension makes the http service unavailable, so using the default configuration (no policy, unbounded buffer) should be preferable. Users should try to avoid memory issues by limiting the number of requests to the http service (e.g., scaling out).
In contexts where a certain amount of data loss is acceptable, setting a backpressure strategy other than BUFFER can be a solution for dealing with fast sources.
-
Java
-
XML
-
YAML
from("direct:thermostat")
.to("reactive-streams:flow?backpressureStrategy=LATEST"); <route>
<from uri="direct:thermostat"/>
<to uri="reactive-streams:flow?backpressureStrategy=LATEST"/>
</route> - route:
from:
uri: direct:thermostat
steps:
- to:
uri: reactive-streams:flow
parameters:
backpressureStrategy: LATEST When the LATEST backpressure strategy is used, the publisher keeps only the last exchange received from the route, while older data is discarded (other options are available).
Controlling Backpressure (consumer side)
When Camel consumes items from a reactive-streams publisher, the maximum number of in-flight exchanges can be set as an endpoint option.
The subscriber associated with the consumer interacts with the publisher to keep the number of messages in the route lower than the threshold.
An example of backpressure-aware route:
-
Java
-
XML
-
YAML
from("reactive-streams:numbers?maxInflightExchanges=10")
.to("direct:endpoint"); <route>
<from uri="reactive-streams:numbers?maxInflightExchanges=10"/>
<to uri="direct:endpoint"/>
</route> - route:
from:
uri: reactive-streams:numbers
parameters:
maxInflightExchanges: 10
steps:
- to:
uri: direct:endpoint The number of items that Camel requests to the source publisher (through the reactive streams backpressure mechanism) is never more than 10. Messages are processed by a single thread in the Camel side.
The number of concurrent consumers (threads) can also be set as endpoint option (concurrentConsumers). When using 1 consumer (the default), the order of items in the source stream is maintained. When this value is increased, items will be processed concurrently by multiple threads (so not preserving the order).
Suspending the consumer
The consumer can be suspended: by suspending its route (route controller, JMX), by a route policy such as ThrottlingInflightRoutePolicy, and during a graceful shutdown. A suspended consumer requests no more items from the publisher and does not route the items it has already received (the items queued for its threads, and the items the publisher still sends for the demand requested before the suspend). The exchanges being routed complete normally, and the suspend does not wait for the queued items: they are routed in order when the consumer is resumed, or when it is stopped.
A graceful shutdown (stopping the route, all the routes or the CamelContext) also suspends the consumer first, but then routes its queued items, and waits for them up to the shutdown timeout, before it stops the routes the items go to, such as a direct or seda route. No more items are requested from the publisher.
When backpressure is disabled (maxInflightExchanges not positive), a suspended consumer cannot limit what the publisher sends: the items it receives while suspended are kept in memory until it is resumed or stopped.