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,*.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 Flink component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
Deprecated The callback that flink endpoints of the dataset type use when they set no dataSetCallback. The DataSet API is deprecated in Apache Flink. | DataSetCallback | ||
The DataStream that flink endpoints of the datastream type use when they set no dataStream. | DataStream | ||
The callback that flink endpoints of the datastream type use when they set no dataStreamCallback. | 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
| Name | Description | Default | Type |
|---|---|---|---|
Whether a DataSet returned by the dataSetCallback is collected into a List with DataSet.collect(), which executes the job; the List is the message body. When false, the DataSet itself is the message body and the CamelFlinkDataSet header. A DataStream returned by the dataStreamCallback is never collected: it is the message body and the CamelFlinkDataStream header, and setting collect to true explicitly fails the exchange. | true | boolean | |
The DataSet to compute on, for the dataset endpoint type. The CamelFlinkDataSet header overrides it; when not set, the dataSet of the component is used. The DataSet API is deprecated in Apache Flink. | DataSet | ||
The callback that the dataset endpoint type calls with the DataSet and the message body as payload (a List body gives one payload per element). What it returns is the message body; a DataSet it returns is collected unless collect is false. The CamelFlinkDataSetCallback header overrides it; when not set, the dataSetCallback of the component is used. | DataSetCallback | ||
The DataStream to compute on, for the datastream endpoint type. The CamelFlinkDataStream header overrides it; when not set, the dataStream of the component is used. | DataStream | ||
The callback that the datastream endpoint type calls with the DataStream and the message body as payload (a List body gives one payload per element). The component does not run the job: the callback builds it and calls execute() on the StreamExecutionEnvironment. What the callback returns is the message body. The CamelFlinkDataStreamCallback header overrides it; when not set, the dataStreamCallback of the component is used. | DataStreamCallback | ||
The checkpointing mode: EXACTLY_ONCE, or AT_LEAST_ONCE (lower latency, but records can be processed more than once after a recovery). When not set, Flink uses EXACTLY_ONCE. An invalid value is logged and ignored. Only applies when checkpointInterval is set. Only for the datastream endpoint type; set on the StreamExecutionEnvironment of the DataStream when the first message is processed. Enum values:
| String | ||
The interval in milliseconds between checkpoints. A value of 10 or more enables checkpointing, a value from 1 to 9 fails, and 0 or a negative value leaves checkpointing as the environment has it. checkpointingMode, checkpointTimeout and minPauseBetweenCheckpoints apply only when checkpointing is enabled by this option. Only for the datastream endpoint type; set on the StreamExecutionEnvironment of the DataStream when the first message is processed. | Long | ||
The time in milliseconds after which a checkpoint in progress is discarded, at least 10. When not set, Flink uses 10 minutes. Only applies when checkpointInterval is set. Only for the datastream endpoint type; set on the StreamExecutionEnvironment of the DataStream when the first message is processed. | Long | ||
The runtime execution mode of the job: STREAMING, BATCH (for bounded streams) or AUTOMATIC (BATCH when all sources are bounded). When not set, the environment keeps its own mode, STREAMING by default. An invalid value is logged and ignored. Only for the datastream endpoint type; set on the StreamExecutionEnvironment of the DataStream when the first message is processed. Enum values:
| String | ||
A name for the Flink job. The component does not use this option: the dataStreamCallback names the job when it calls execute(jobName) on the StreamExecutionEnvironment. | 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 | |
The maximum parallelism of the job, from 1 to 32768: the upper limit for rescaling and the number of key groups of keyed state. When not set, Flink derives it from the parallelism (at least 128). Only for the datastream endpoint type; set on the StreamExecutionEnvironment of the DataStream when the first message is processed. | Integer | ||
The minimum time in milliseconds between the end of a checkpoint and the start of the next one, 0 or more. When not set, Flink uses 0. Only applies when checkpointInterval is set. Only for the datastream endpoint type; set on the StreamExecutionEnvironment of the DataStream when the first message is processed. | Long | ||
The default parallelism of the operators of the job: at least 1, or -1 for the default of the Flink configuration. When not set, the environment keeps its own parallelism. Only for the datastream endpoint type; set on the StreamExecutionEnvironment of the DataStream when the first message is processed. | Integer |
Message Headers
The Flink component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
| Constant: | The DataSet to compute on, which overrides the dataSet option. When collect is false and the dataSetCallback returns a DataSet, the producer sets this header to that DataSet. | Object | |
CamelFlinkDataSetCallback (producer) Constant: | The callback to call with the DataSet, which overrides the dataSetCallback option. | DataSetCallback | |
CamelFlinkDataStream (producer) Constant: | The DataStream to compute on, which overrides the dataStream option. When the dataStreamCallback returns a DataStream, the producer sets this header to that DataStream. | Object | |
CamelFlinkDataStreamCallback (producer) Constant: | The callback to call with the DataStream, which overrides the dataStreamCallback option. | DataStreamCallback |
Message Body
The message body at each side of the Flink 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 body is handed to the DataSet or DataStream callback as its payload, a List as one payload per element; the data to compute on is the DataSet or DataStream of the endpoint or of the CamelFlinkDataSet or CamelFlinkDataStream header. |
Producer output |
| What the callback returns, null for a void callback. A DataSet it returns is collected into a List unless collect is false; a DataStream it returns is not collected (it fails if collect is explicitly set to true). A DataSet or DataStream that is not collected is the body and the CamelFlinkDataSet or CamelFlinkDataStream 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.
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();
}
};
} Then use the beans in the route:
-
Java
-
XML
-
YAML
from("direct:wordCount")
.to("flink:datastream?dataStream=#myDataStream&dataStreamCallback=#wordCountCallback"); <route>
<from uri="direct:wordCount"/>
<to uri="flink:datastream?dataStream=#myDataStream&dataStreamCallback=#wordCountCallback"/>
</route> - route:
from:
uri: direct:wordCount
steps:
- to:
uri: flink:datastream
parameters:
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:
-
Java
-
XML
-
YAML
from("direct:batchProcess")
.to("flink:datastream?dataStream=#myDataStream&dataStreamCallback=#myCallback&executionMode=BATCH¶llelism=4&jobName=MyBatchJob"); <route>
<from uri="direct:batchProcess"/>
<to uri="flink:datastream?dataStream=#myDataStream&dataStreamCallback=#myCallback&executionMode=BATCH&parallelism=4&jobName=MyBatchJob"/>
</route> - route:
from:
uri: direct:batchProcess
steps:
- to:
uri: flink:datastream
parameters:
dataStream: "#myDataStream"
dataStreamCallback: "#myCallback"
executionMode: BATCH
parallelism: 4
jobName: MyBatchJob Streaming with Checkpointing
Configure a streaming job with checkpointing for fault tolerance:
-
Java
-
XML
-
YAML
from("direct:streamProcess")
.to("flink:datastream?dataStream=#myDataStream&dataStreamCallback=#streamCallback&executionMode=STREAMING&checkpointInterval=60000&checkpointingMode=EXACTLY_ONCE&checkpointTimeout=120000&minPauseBetweenCheckpoints=30000¶llelism=8&maxParallelism=128&jobName=StreamingPipeline"); <route>
<from uri="direct:streamProcess"/>
<to uri="flink:datastream?dataStream=#myDataStream&dataStreamCallback=#streamCallback&executionMode=STREAMING&checkpointInterval=60000&checkpointingMode=EXACTLY_ONCE&checkpointTimeout=120000&minPauseBetweenCheckpoints=30000&parallelism=8&maxParallelism=128&jobName=StreamingPipeline"/>
</route> - route:
from:
uri: direct:streamProcess
steps:
- to:
uri: flink:datastream
parameters:
dataStream: "#myDataStream"
dataStreamCallback: "#streamCallback"
executionMode: STREAMING
checkpointInterval: 60000
checkpointingMode: EXACTLY_ONCE
checkpointTimeout: 120000
minPauseBetweenCheckpoints: 30000
parallelism: 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 | Derived from the parallelism (at least 128) | Maximum parallelism, which defines the upper bound for dynamic scaling. |
jobName | String | null | Name for the Flink job. Not used by the component: the callback names the job when it calls |
collect | Boolean | true | Whether to collect the DataSet returned by a dataset callback into a List. A DataStream returned by a datastream callback is not collected: it is the message body and the |