Flink
Since Camel 2.18
Only producer is supported
This documentation page covers the Apache Flink component for the Apache Camel. The camel-flink component provides a bridge between Camel components and Flink tasks. This component provides a way to route a message from various transports, dynamically choosing a flink task to execute, use an incoming message as input data for the task and finally deliver the results back to the Camel pipeline.
Maven users will need to add the following dependency to their pom.xml
for this component:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-flink</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency>
URI Format
Currently, the Flink Component supports only Producers. One can create DataSet, DataStream jobs.
flink:dataset?dataset=#myDataSet&dataSetCallback=#dataSetCallback flink:datastream?datastream=#myDataStream&dataStreamCallback=#dataStreamCallback
The DataSet API has been deprecated by Apache Flink since version 1.12. It is recommended to migrate to the DataStream API with bounded streams for batch processing. See the Migration Guide section below for more details. |
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
,*.yaml
files, 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 Flink component supports 5 options, which are listed below.
Name | Description | Default | Type |
---|---|---|---|
Deprecated Function performing action against a DataSet. | DataSetCallback | ||
DataStream to compute against. | DataStream | ||
Function performing action against a DataStream. | DataStreamCallback | ||
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 Flink endpoint is configured using URI syntax:
flink:endpointType
With the following path and query parameters:
Query Parameters (14 parameters)
Name | Description | Default | Type |
---|---|---|---|
Indicates if results should be collected or counted. | true | boolean | |
DataSet to compute against. | DataSet | ||
Function performing action against a DataSet. | DataSetCallback | ||
DataStream to compute against. | DataStream | ||
Function performing action against a DataStream. | DataStreamCallback | ||
Checkpointing mode: EXACTLY_ONCE (default) or AT_LEAST_ONCE. EXACTLY_ONCE provides stronger guarantees but may have higher overhead. Enum values:
| String | ||
Interval in milliseconds between checkpoints. Enables checkpointing when set. Recommended for streaming jobs to ensure fault tolerance. | Long | ||
Timeout in milliseconds for checkpoints. Checkpoints that take longer will be aborted. | Long | ||
Execution mode for the Flink job. Options: STREAMING (default), BATCH, AUTOMATIC. BATCH mode is recommended for bounded streams (batch processing). Enum values:
| String | ||
Name for the Flink job. Useful for identification in the Flink UI and logs. | String | ||
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 | |
Maximum parallelism for the Flink job. Defines the upper bound for dynamic scaling and the number of key groups for stateful operators. | Integer | ||
Minimum pause in milliseconds between consecutive checkpoints. Helps prevent checkpoint storms under heavy load. | Long | ||
Parallelism for the Flink job. If not set, uses the default parallelism of the execution environment. | Integer |
Message Headers
The Flink component supports 4 message header(s), which is/are listed below:
Name | Description | Default | Type |
---|---|---|---|
Constant: | The dataset. | Object | |
CamelFlinkDataSetCallback (producer) Constant: | The dataset callback. | DataSetCallback | |
CamelFlinkDataStream (producer) Constant: | The data stream. | Object | |
CamelFlinkDataStreamCallback (producer) Constant: | The data stream callback. | DataStreamCallback |
Examples
Flink DataSet Callback
@Bean
public DataSetCallback<Long> dataSetCallback() {
return new DataSetCallback<Long>() {
public Long onDataSet(DataSet dataSet, Object... objects) {
try {
dataSet.print();
return new Long(0);
} catch (Exception e) {
return new Long(-1);
}
}
};
}
Flink DataStream Callback
@Bean
public VoidDataStreamCallback dataStreamCallback() {
return new VoidDataStreamCallback() {
@Override
public void doOnDataStream(DataStream dataStream, Object... objects) throws Exception {
dataStream.flatMap(new Splitter()).print();
environment.execute("data stream test");
}
};
}
Camel-Flink Producer call
CamelContext camelContext = new SpringCamelContext(context);
String pattern = "foo";
try {
ProducerTemplate template = camelContext.createProducerTemplate();
camelContext.start();
Long count = template.requestBody("flink:dataSet?dataSet=#myDataSet&dataSetCallback=#countLinesContaining", pattern, Long.class);
} finally {
camelContext.stop();
}
Modern DataStream Batch Processing Example
The recommended approach using the DataStream API in batch mode:
@Bean
public StreamExecutionEnvironment streamExecutionEnvironment() {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// Configure for batch processing
env.setRuntimeMode(RuntimeExecutionMode.BATCH);
return env;
}
@Bean
public DataStreamSource<String> myDataStream(StreamExecutionEnvironment env) {
return env.readTextFile("src/test/resources/testds.txt");
}
@Bean
public DataStreamCallback wordCountCallback() {
return new VoidDataStreamCallback() {
@Override
public void doOnDataStream(DataStream dataStream, Object... payloads) throws Exception {
dataStream
.flatMap((String line, Collector<Tuple2<String, Integer>> out) -> {
for (String word : line.split("\\s+")) {
out.collect(Tuple2.of(word, 1));
}
})
.returns(Types.TUPLE(Types.STRING, Types.INT))
.keyBy(tuple -> tuple.f0)
.sum(1)
.print();
}
};
}
// In your route
from("direct:wordCount")
.to("flink:datastream?dataStream=#myDataStream&dataStreamCallback=#wordCountCallback");
Real-time Streaming Example
For true streaming use cases with unbounded data:
@Bean
public StreamExecutionEnvironment streamingEnvironment() {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// Configure for streaming (default mode)
env.setRuntimeMode(RuntimeExecutionMode.STREAMING);
// Enable checkpointing for fault tolerance
env.enableCheckpointing(10000); // checkpoint every 10 seconds
return env;
}
@Bean
public DataStreamCallback streamingProcessCallback() {
return new VoidDataStreamCallback() {
@Override
public void doOnDataStream(DataStream dataStream, Object... payloads) throws Exception {
dataStream
.map(event -> processEvent(event))
.keyBy(event -> event.getKey())
.window(TumblingEventTimeWindows.of(Time.minutes(5)))
.aggregate(new MyAggregateFunction())
.addSink(new MyCustomSink());
// Execute the streaming job
dataStream.getExecutionEnvironment().execute("Streaming Job");
}
};
}
Advanced Configuration Examples
Batch Processing with Configuration
Configure a DataStream endpoint for batch processing with custom settings:
from("direct:batchProcess")
.to("flink:datastream?dataStream=#myDataStream"
+ "&dataStreamCallback=#myCallback"
+ "&executionMode=BATCH"
+ "¶llelism=4"
+ "&jobName=MyBatchJob");
Streaming with Checkpointing
Configure a streaming job with checkpointing for fault tolerance:
from("direct:streamProcess")
.to("flink:datastream?dataStream=#myDataStream"
+ "&dataStreamCallback=#streamCallback"
+ "&executionMode=STREAMING"
+ "&checkpointInterval=60000" // Checkpoint every 60 seconds
+ "&checkpointingMode=EXACTLY_ONCE" // Exactly-once semantics
+ "&checkpointTimeout=120000" // 2 minute timeout
+ "&minPauseBetweenCheckpoints=30000" // 30 second minimum pause
+ "¶llelism=8"
+ "&maxParallelism=128"
+ "&jobName=StreamingPipeline");
Configuration Options Reference
Parameter | Type | Default | Description |
---|---|---|---|
executionMode | String | STREAMING | Runtime execution mode: STREAMING, BATCH, or AUTOMATIC. BATCH is recommended for bounded streams. |
checkpointInterval | Long | null | Checkpoint interval in milliseconds. Setting this enables checkpointing. |
checkpointingMode | String | EXACTLY_ONCE | Checkpointing mode: EXACTLY_ONCE or AT_LEAST_ONCE. |
checkpointTimeout | Long | 10 minutes | Maximum time in milliseconds that a checkpoint may take. |
minPauseBetweenCheckpoints | Long | 0 | Minimum time in milliseconds between consecutive checkpoints. |
parallelism | Integer | Default parallelism | Parallelism for the Flink job operations. |
maxParallelism | Integer | 128 | Maximum parallelism, which defines the upper bound for dynamic scaling. |
jobName | String | null | Name for the Flink job, useful for identification in Flink UI. |
collect | Boolean | true | Whether to collect results (not applicable for unbounded streams). |
Common Patterns
Spring Boot Auto-Configuration
When using flink with Spring Boot make sure to use the following Maven dependency to have support for auto configuration:
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-flink-starter</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency>
The component supports 6 options, which are listed below.
Name | Description | Default | Type |
---|---|---|---|
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 | |
DataStream to compute against. The option is a org.apache.flink.streaming.api.datastream.DataStream type. | DataStream | ||
Function performing action against a DataStream. The option is a org.apache.camel.component.flink.DataStreamCallback type. | DataStreamCallback | ||
Whether to enable auto configuration of the flink component. This is enabled by default. | 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 | |
Deprecated Function performing action against a DataSet. The option is a org.apache.camel.component.flink.DataSetCallback type. | DataSetCallback |