이 콘텐츠는 선택한 언어로 제공되지 않습니다.

Chapter 134. Spring Batch


Since Camel 2.10

Only producer is supported

The Spring Batch component and support classes provide integration bridge between Camel and Spring Batch infrastructure.

134.1. Dependencies

When using spring-batch with Red Hat build of Camel Spring Boot, use the following Maven dependency to enable support for auto-configuration:

<dependency>
  <groupId>org.apache.camel.springboot</groupId>
  <artifactId>camel-spring-batch-starter</artifactId>
</dependency>
Copy to Clipboard

134.2. URI format

spring-batch:jobName[?options]
Copy to Clipboard

Where, jobName represents the name of the Spring Batch job located in the Camel registry. If a JobRegistry is provided is used to locate the job.

This component is only used to define producer endpoints, that means you cannot use the Spring Batch component in a from() statement.

134.3. Configuring Options

Camel components are configured on two separate levels:

  • component level
  • endpoint level

134.3.1. 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.

134.3.2. 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.

134.4. Component Options

The Spring Batch component supports 4 options, which are listed below.

NameDescriptionDefaultType

jobLauncher (producer)

Explicitly specifies a JobLauncher to be used.

 

JobLauncher

jobRegistry (producer)

Explicitly specifies a JobRegistry to be used.

 

JobRegistry

lazyStartProducer (producer)

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

autowiredEnabled (advanced)

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

134.5. Endpoint Options

The Spring Batch endpoint is configured using URI syntax:

spring-batch:jobName
Copy to Clipboard

Following are the path and query parameters:

134.5.1. Path Parameters (1 parameters)

NameDescriptionDefaultType

jobName (producer)

Required The name of the Spring Batch job located in the registry.

 

String

134.5.2. Query Parameters (4 parameters)

NameDescriptionDefaultType

jobFromHeader (producer)

Explicitly defines if the jobName should be taken from the headers instead of the URI.

false

boolean

jobLauncher (producer)

Explicitly specifies a JobLauncher to be used.

 

JobLauncher

jobRegistry (producer)

Explicitly specifies a JobRegistry to be used.

 

JobRegistry

lazyStartProducer (producer (advanced))

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

134.6. Usage

When Spring Batch component receives the message, it triggers the job execution. The job is executed using the org.springframework.batch.core.launch.JobLaucher instance resolved according to the following algorithm.

  • if JobLauncher is manually set on the component, then use it.
  • if jobLauncherRef option is set on the component, then search Camel Registry for the JobLauncher with the given name.
  • if there is JobLauncher registered in the Camel Registry under jobLauncher name, then use it.
  • if none of the steps above allow to resolve the JobLauncher and there is exactly one JobLauncher instance in the Camel Registry, then use it.

All headers found in the message are passed to the JobLauncher as job parameters. String, Long, Double and java.util.Date values are copied to the org.springframework.batch.core.JobParametersBuilder and other data types are converted to Strings.

134.7. Examples

Triggering the Spring Batch job execution:

from("direct:startBatch").to("spring-batch:myJob");
Copy to Clipboard

Triggering the Spring Batch job execution with the JobLauncher set explicitly.

from("direct:startBatch").to("spring-batch:myJob?jobLauncherRef=myJobLauncher");
Copy to Clipboard

A JobExecution instance returned by the JobLauncher is forwarded by the SpringBatchProducer as the output message. You can use the JobExecution instance to perform some operations using the Spring Batch API directly.

from("direct:startBatch").to("spring-batch:myJob").to("mock:JobExecutions");
...
MockEndpoint mockEndpoint = ...;
JobExecution jobExecution = mockEndpoint.getExchanges().get(0).getIn().getBody(JobExecution.class);
BatchStatus currentJobStatus = jobExecution.getStatus();
Copy to Clipboard

134.8. Support classes

Apart from the component, Camel Spring Batch also provides support classes that you can use to hook into Spring Batch infrastructure.

134.8.1. CamelItemReader

CamelItemReader can be used to read batch data directly from the Camel infrastructure.

For example, the snippet below configures Spring Batch to read data from JMS queue:

<bean id="camelReader" class="org.apache.camel.component.spring.batch.support.CamelItemReader">
  <constructor-arg ref="consumerTemplate"/>
  <constructor-arg value="jms:dataQueue"/>
</bean>

<batch:job id="myJob">
  <batch:step id="step">
    <batch:tasklet>
      <batch:chunk reader="camelReader" writer="someWriter" commit-interval="100"/>
    </batch:tasklet>
  </batch:step>
</batch:job>
Copy to Clipboard

134.8.2. CamelItemWriter

CamelItemWriter has similar purpose as CamelItemReader, but it is dedicated to write chunk of the processed data.

For example the snippet below configures Spring Batch to read data from JMS queue.

<bean id="camelwriter" class="org.apache.camel.component.spring.batch.support.CamelItemWriter">
  <constructor-arg ref="producerTemplate"/>
  <constructor-arg value="jms:dataQueue"/>
</bean>

<batch:job id="myJob">
  <batch:step id="step">
    <batch:tasklet>
      <batch:chunk reader="someReader" writer="camelwriter" commit-interval="100"/>
    </batch:tasklet>
  </batch:step>
</batch:job>
Copy to Clipboard

134.8.3. CamelItemProcessor

CamelItemProcessor is the implementation of Spring Batch org.springframework.batch.item.ItemProcessor interface. The latter implementation relays on Request Reply pattern to delegate the processing of the batch item to the Camel infrastructure. The item to process is sent to the Camel endpoint as the body of the message.

For example the snippet below performs simple processing of the batch item using the Direct endpoint and the Simple expression language.

<camel:camelContext>
  <camel:route>
    <camel:from uri="direct:processor"/>
    <camel:setExchangePattern pattern="InOut"/>
    <camel:setBody>
      <camel:simple>Processed ${body}</camel:simple>
    </camel:setBody>
  </camel:route>
</camel:camelContext>

<bean id="camelProcessor" class="org.apache.camel.component.spring.batch.support.CamelItemProcessor">
  <constructor-arg ref="producerTemplate"/>
  <constructor-arg value="direct:processor"/>
</bean>

<batch:job id="myJob">
  <batch:step id="step">
    <batch:tasklet>
      <batch:chunk reader="someReader" writer="someWriter" processor="camelProcessor" commit-interval="100"/>
    </batch:tasklet>
  </batch:step>
</batch:job>
Copy to Clipboard

134.8.4. CamelJobExecutionListener

CamelJobExecutionListener is the implementation of the org.springframework.batch.core.JobExecutionListener interface sending job execution events to the Camel endpoint.

The org.springframework.batch.core.JobExecution instance produced by the Spring Batch is sent as a body of the message. To distinguish between before- and after-callbacks SPRING_BATCH_JOB_EVENT_TYPE header is set to the BEFORE or AFTER value.

The example snippet below sends Spring Batch job execution events to the JMS queue.

<bean id="camelJobExecutionListener" class="org.apache.camel.component.spring.batch.support.CamelJobExecutionListener">
  <constructor-arg ref="producerTemplate"/>
  <constructor-arg value="jms:batchEventsBus"/>
</bean>

<batch:job id="myJob">
  <batch:step id="step">
    <batch:tasklet>
      <batch:chunk reader="someReader" writer="someWriter" commit-interval="100"/>
    </batch:tasklet>
  </batch:step>
  <batch:listeners>
    <batch:listener ref="camelJobExecutionListener"/>
  </batch:listeners>
</batch:job>
Copy to Clipboard

134.9. Spring Boot Auto-Configuration

The component supports 5 options, which are listed below.

NameDescriptionDefaultType

camel.component.spring-batch.autowired-enabled

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

camel.component.spring-batch.enabled

Whether to enable auto-configuration of the spring-batch component. This is enabled by default.

 

Boolean

camel.component.spring-batch.job-launcher

Explicitly specifies a JobLauncher to be used. The option is a org.springframework.batch.core.launch.JobLauncher type.

 

JobLauncher

camel.component.spring-batch.job-registry

Explicitly specifies a JobRegistry to be used. The option is a org.springframework.batch.core.configuration.JobRegistry type.

 

JobRegistry

camel.component.spring-batch.lazy-start-producer

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

맨 위로 이동
Red Hat logoGithubredditYoutubeTwitter

자세한 정보

평가판, 구매 및 판매

커뮤니티

Red Hat 문서 정보

Red Hat을 사용하는 고객은 신뢰할 수 있는 콘텐츠가 포함된 제품과 서비스를 통해 혁신하고 목표를 달성할 수 있습니다. 최신 업데이트를 확인하세요.

보다 포괄적 수용을 위한 오픈 소스 용어 교체

Red Hat은 코드, 문서, 웹 속성에서 문제가 있는 언어를 교체하기 위해 최선을 다하고 있습니다. 자세한 내용은 다음을 참조하세요.Red Hat 블로그.

Red Hat 소개

Red Hat은 기업이 핵심 데이터 센터에서 네트워크 에지에 이르기까지 플랫폼과 환경 전반에서 더 쉽게 작업할 수 있도록 강화된 솔루션을 제공합니다.

Theme

© 2025 Red Hat