13. 集成 Spring Batch

13.1. Spring Batch Integration Introduction

Many users of Spring Batch may encounter requirements that are outside the scope of Spring Batch, yet may be efficiently and concisely implemented using Spring Integration. Conversely, Spring Batch users may encounter Spring Batch requirements and need a way to efficiently integrate both frameworks. In this context several patterns and use-cases emerge and Spring Batch Integration will address those requirements.

The line between Spring Batch and Spring Integration is not always clear, but there are guidelines that one can follow. Principally, these are: think about granularity, and apply common patterns. Some of those common patterns are described in this reference manual section.

Adding messaging to a batch process enables automation of operations, and also separation and strategizing of key concerns. For example a message might trigger a job to execute, and then the sending of the message can be exposed in a variety of ways. Or when a job completes or fails that might trigger a message to be sent, and the consumers of those messages might have operational concerns that have nothing to do with the application itself. Messaging can also be embedded in a job, for example reading or writing items for processing via channels. Remote partitioning and remote chunking provide methods to distribute workloads over an number of workers.

Some key concepts that we will cover are:

  • Namespace Support

  • Launching Batch Jobs through Messages

  • Providing Feedback with Informational Messages

  • Asynchronous Processors

  • Externalizing Batch Process Execution

13.1.1. Namespace Support

Since Spring Batch Integration 1.3, dedicated XML Namespace support was added, with the aim to provide an easier configuration experience. In order to activate the namespace, add the following namespace declarations to your Spring XML Application Context file:

  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns:batch-int="http://www.springframework.org/schema/batch-integration"
  4. xsi:schemaLocation="
  5. http://www.springframework.org/schema/batch-integration
  6. http://www.springframework.org/schema/batch-integration/spring-batch-integration.xsd">
  7. ...
  8. </beans>

A fully configured Spring XML Application Context file for Spring Batch Integration may look like the following:

  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns:int="http://www.springframework.org/schema/integration"
  4. xmlns:batch="http://www.springframework.org/schema/batch"
  5. xmlns:batch-int="http://www.springframework.org/schema/batch-integration"
  6. xsi:schemaLocation="
  7. http://www.springframework.org/schema/batch-integration
  8. http://www.springframework.org/schema/batch-integration/spring-batch-integration.xsd
  9. http://www.springframework.org/schema/batch
  10. http://www.springframework.org/schema/batch/spring-batch.xsd
  11. http://www.springframework.org/schema/beans
  12. http://www.springframework.org/schema/beans/spring-beans.xsd
  13. http://www.springframework.org/schema/integration
  14. http://www.springframework.org/schema/integration/spring-integration.xsd">
  15. ...
  16. </beans>

Appending version numbers to the referenced XSD file is also allowed but, as a version-less declaration will always use the latest schema, we generally don’t recommend appending the version number to the XSD name. Adding a version number, for instance, would create possibly issues when updating the Spring Batch Integration dependencies as they may require more recent versions of the XML schema.

13.1.2. Launching Batch Jobs through Messages

When starting batch jobs using the core Spring Batch API you basically have 2 options:

  • Command line via the CommandLineJobRunner
  • Programatically via either JobOperator.start() or JobLauncher.run().

For example, you may want to use the CommandLineJobRunner when invoking Batch Jobs using a shell script. Alternatively, you may use the JobOperator directly, for example when using Spring Batch as part of a web application. However, what about more complex use-cases? Maybe you need to poll a remote (S)FTP server to retrieve the data for the Batch Job. Or your application has to support multiple different data sources simultaneously. For example, you may receive data files not only via the web, but also FTP etc. Maybe additional transformation of the input files is needed before invoking Spring Batch.

Therefore, it would be much more powerful to execute the batch job using Spring Integration and its numerous adapters. For example, you can use a File Inbound Channel Adapter to monitor a directory in the file-system and start the Batch Job as soon as the input file arrives. Additionally you can create Spring Integration flows that use multiple different adapters to easily ingest data for your Batch Jobs from multiple sources simultaneously using configuration only. Implementing all these scenarios with Spring Integration is easy as it allow for an decoupled event-driven execution of the JobLauncher.

Spring Batch Integration provides the JobLaunchingMessageHandler class that you can use to launch batch jobs. The input for the JobLaunchingMessageHandler is provided by a Spring Integration message, which payload is of type JobLaunchRequest. This class is a wrapper around the Job that needs to be launched as well as the JobParameters necessary to launch the Batch job.

The following image illustrates the typical Spring Integration message flow in order to start a Batch job. The EIP (Enterprise IntegrationPatterns) website provides a full overview of messaging icons and their descriptions.

Spring Batch Integration模块 - 图1

Transforming a file into a JobLaunchRequest

  1. package io.spring.sbi;
  2. import org.springframework.batch.core.Job;
  3. import org.springframework.batch.core.JobParametersBuilder;
  4. import org.springframework.batch.integration.launch.JobLaunchRequest;
  5. import org.springframework.integration.annotation.Transformer;
  6. import org.springframework.messaging.Message;
  7. import java.io.File;
  8. public class FileMessageToJobRequest {
  9. private Job job;
  10. private String fileParameterName;
  11. public void setFileParameterName(String fileParameterName) {
  12. this.fileParameterName = fileParameterName;
  13. }
  14. public void setJob(Job job) {
  15. this.job = job;
  16. }
  17. @Transformer
  18. public JobLaunchRequest toRequest(Message<File> message) {
  19. JobParametersBuilder jobParametersBuilder =
  20. new JobParametersBuilder();
  21. jobParametersBuilder.addString(fileParameterName,
  22. message.getPayload().getAbsolutePath());
  23. return new JobLaunchRequest(job, jobParametersBuilder.toJobParameters());
  24. }
  25. }

The JobExecution Response

When a Batch Job is being executed, a JobExecution instance is returned. This instance can be used to determine the status of an execution. If a JobExecution was able to be created successfully, it will always be returned, regardless of whether or not the actual execution was successful.

The exact behavior on how the JobExecution instance is returned depends on the provided TaskExecutor. If a synchronous (single-threaded) TaskExecutor implementation is used, the JobExecution response is only returned after the job completes. When using an asynchronous TaskExecutor, the JobExecution instance is returned immediately. Users can then take the id of JobExecution instance (JobExecution.getJobId()) and query the JobRepository for the job’s updated status using the JobExplorer. For more information, please refer to the Spring Batch reference documentation on Querying the Repository.

The following configuration will create a file inbound-channel-adapter to listen for CSV files in the provided directory, hand them off to our transformer (FileMessageToJobRequest), launch the job via the Job Launching Gateway then simply log the output of the JobExecution via the logging-channel-adapter.

Spring Batch Integration Configuration

  1. <int:channel id="inboundFileChannel"/>
  2. <int:channel id="outboundJobRequestChannel"/>
  3. <int:channel id="jobLaunchReplyChannel"/>
  4. <int-file:inbound-channel-adapter id="filePoller"
  5. channel="inboundFileChannel"
  6. directory="file:/tmp/myfiles/"
  7. filename-pattern="*.csv">
  8. <int:poller fixed-rate="1000"/>
  9. </int-file:inbound-channel-adapter>
  10. <int:transformer input-channel="inboundFileChannel"
  11. output-channel="outboundJobRequestChannel">
  12. <bean class="io.spring.sbi.FileMessageToJobRequest">
  13. <property name="job" ref="personJob"/>
  14. <property name="fileParameterName" value="input.file.name"/>
  15. </bean>
  16. </int:transformer>
  17. <batch-int:job-launching-gateway request-channel="outboundJobRequestChannel"
  18. reply-channel="jobLaunchReplyChannel"/>
  19. <int:logging-channel-adapter channel="jobLaunchReplyChannel"/>

Now that we are polling for files and launching jobs, we need to configure for example our Spring Batch ItemReader to utilize found file represented by the job parameter “input.file.name”:

Example ItemReader Configuration

  1. <bean id="itemReader" class="org.springframework.batch.item.file.FlatFileItemReader"
  2. scope="step">
  3. <property name="resource" value="file://#{jobParameters['input.file.name']}"/>
  4. ...
  5. </bean>

The main points of interest here are injecting the value of #{jobParameters[‘input.file.name’]} as the Resource property value and setting the ItemReader bean to be of Step scope to take advantage of the late binding support which allows access to the jobParameters variable.

Available Attributes of the Job-Launching Gateway

  • id Identifies the underlying Spring bean definition, which is an instance of either:

    • EventDrivenConsumer
    • PollingConsumer

      The exact implementation depends on whether the component’s input channel is a:

    • SubscribableChannel or

    • PollableChannel
  • auto-startup Boolean flag to indicate that the endpoint should start automatically on startup. The default istrue.

  • request-channel The input MessageChannel of this endpoint.

  • reply-channel Message Channel to which the resulting JobExecution payload will be sent.

  • reply-timeout Allows you to specify how long this gateway will wait for the reply message to be sent successfully to the reply channel before throwing an exception. This attribute only applies when the channel might block, for example when using a bounded queue channel that is currently full. Also, keep in mind that when sending to a DirectChannel, the invocation will occur in the sender’s thread. Therefore, the failing of the send operation may be caused by other components further downstream. The reply-timeout attribute maps to the sendTimeout property of the underlying MessagingTemplate instance. The attribute will default, if not specified, to-1, meaning that by default, the Gateway will wait indefinitely. The value is specified in milliseconds.

  • job-launcher Pass in a custom JobLauncher bean reference. This attribute is optional. If not specified the adapter will re-use the instance that is registered under the id jobLauncher. If no default instance exists an exception is thrown.

  • order Specifies the order for invocation when this endpoint is connected as a subscriber to a SubscribableChannel.

Sub-Elements

When this Gateway is receiving messages from a PollableChannel, you must either provide a global default Poller or provide a Poller sub-element to the Job Launching Gateway:

  1. <batch-int:job-launching-gateway request-channel="queueChannel"
  2. reply-channel="replyChannel" job-launcher="jobLauncher">
  3. <int:poller fixed-rate="1000"/>
  4. </batch-int:job-launching-gateway>

13.1.3. Providing Feedback with Informational Messages

As Spring Batch jobs can run for long times, providing progress information will be critical. For example, stake-holders may want to be notified if a some or all parts of a Batch Job has failed. Spring Batch provides support for this information being gathered through:

  • Active polling or
  • Event-driven, using listeners.

When starting a Spring Batch job asynchronously, e.g. by using the Job Launching Gateway, a JobExecution instance is returned. Thus, JobExecution.getJobId() can be used to continuously poll for status updates by retrieving updated instances of the JobExecution from the JobRepository using the JobExplorer. However, this is considered sub-optimal and an event-driven approach should be preferred.

Therefore, Spring Batch provides listeners such as:

  • StepListener
  • ChunkListener
  • JobExecutionListener

In the following example, a Spring Batch job was configured with a StepExecutionListener. Thus, Spring Integration will receive and process any step before/after step events. For example, the received StepExecution can be inspected using a Router. Based on the results of that inspection, various things can occur for example routing a message to a Mail Outbound Channel Adapter, so that an Email notification can be send out based on some condition.

Spring Batch Integration模块 - 图2

Below is an example of how a listener is configured to send a message to a Gateway for StepExecution events and log its output to a logging-channel-adapter:

First create the notifications integration beans:

  1. <int:channel id="stepExecutionsChannel"/>
  2. <int:gateway id="notificationExecutionsListener"
  3. service-interface="org.springframework.batch.core.StepExecutionListener"
  4. default-request-channel="stepExecutionsChannel"/>
  5. <int:logging-channel-adapter channel="stepExecutionsChannel"/>

Then modify your job to add a step level listener:

  1. <job id="importPayments">
  2. <step id="step1">
  3. <tasklet ../>
  4. <chunk ../>
  5. <listeners>
  6. <listener ref="notificationExecutionsListener"/>
  7. </listeners>
  8. </tasklet>
  9. ...
  10. </step>
  11. </job>

13.1.4. Asynchronous Processors

Asynchronous Processors help you to to scale the processing of items. In the asynchronous processor use-case, an AsyncItemProcessor serves as a dispatcher, executing the ItemProcessor’s logic for an item on a new thread. The Future is passed to the AsynchItemWriter to be written once the processor completes.

Therefore, you can increase performance by using asynchronous item processing, basically allowing you to implement fork-join scenarios. The AsyncItemWriter will gather the results and write back the chunk as soon as all the results become available.

Configuration of both the AsyncItemProcessor and AsyncItemWriter are simple, first the AsyncItemProcessor:

  1. <bean id="processor"
  2. class="org.springframework.batch.integration.async.AsyncItemProcessor">
  3. <property name="delegate">
  4. <bean class="your.ItemProcessor"/>
  5. </property>
  6. <property name="taskExecutor">
  7. <bean class="org.springframework.core.task.SimpleAsyncTaskExecutor"/>
  8. </property>
  9. </bean>

The property “delegate” is actually a reference to your ItemProcessor bean and the “taskExecutor” property is a reference to the TaskExecutor of your choice.

Then we configure the AsyncItemWriter:

  1. <bean id="itemWriter"
  2. class="org.springframework.batch.integration.async.AsyncItemWriter">
  3. <property name="delegate">
  4. <bean id="itemWriter" class="your.ItemWriter"/>
  5. </property>
  6. </bean>

Again, the property “delegate” is actually a reference to your ItemWriter bean.

13.1.5. Externalizing Batch Process Execution

The integration approaches discussed so far suggest use-cases where Spring Integration wraps Spring Batch like an outer-shell. However, Spring Batch can also use Spring Integration internally. Using this approach, Spring Batch users can delegate the processing of items or even chunks to outside processes. This allows you to offload complex processing. Spring Batch Integration provides dedicated support for:

  • Remote Chunking
  • Remote Partitioning

Remote Chunking

Spring Batch Integration模块 - 图3

Taking things one step further, one can also externalize the chunk processing using the ChunkMessageChannelItemWriter which is provided by Spring Batch Integration which will send items out and collect the result. Once sent, Spring Batch will continue the process of reading and grouping items, without waiting for the results. Rather it is the responsibility of the ChunkMessageChannelItemWriter to gather the results and integrate them back into the Spring Batch process.

Using Spring Integration you have full control over the concurrency of your processes, for instance by using a QueueChannel instead of a DirectChannel. Furthermore, by relying on Spring Integration’s rich collection of Channel Adapters (E.g. JMS or AMQP), you can distribute chunks of a Batch job to external systems for processing.

A simple job with a step to be remotely chunked would have a configuration similar to the following:

  1. <job id="personJob">
  2. <step id="step1">
  3. <tasklet>
  4. <chunk reader="itemReader" writer="itemWriter" commit-interval="200"/>
  5. </tasklet>
  6. ...
  7. </step>
  8. </job>

The ItemReader reference would point to the bean you would like to use for reading data on the master. The ItemWriter reference points to a special ItemWriter “ChunkMessageChannelItemWriter” as described above. The processor (if any) is left off the master configuration as it is configured on the slave. The following configuration provides a basic master setup. It’s advised to check any additional component properties such as throttle limits and so on when implementing your use case.

  1. <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
  2. <property name="brokerURL" value="tcp://localhost:61616"/>
  3. </bean>
  4. <int-jms:outbound-channel-adapter id="requests" destination-name="requests"/>
  5. <bean id="messagingTemplate"
  6. class="org.springframework.integration.core.MessagingTemplate">
  7. <property name="defaultChannel" ref="requests"/>
  8. <property name="receiveTimeout" value="2000"/>
  9. </bean>
  10. <bean id="itemWriter"
  11. class="org.springframework.batch.integration.chunk.ChunkMessageChannelItemWriter"
  12. scope="step">
  13. <property name="messagingOperations" ref="messagingTemplate"/>
  14. <property name="replyChannel" ref="replies"/>
  15. </bean>
  16. <bean id="chunkHandler"
  17. class="org.springframework.batch.integration.chunk.RemoteChunkHandlerFactoryBean">
  18. <property name="chunkWriter" ref="itemWriter"/>
  19. <property name="step" ref="step1"/>
  20. </bean>
  21. <int:channel id="replies">
  22. <int:queue/>
  23. </int:channel>
  24. <int-jms:message-driven-channel-adapter id="jmsReplies"
  25. destination-name="replies"
  26. channel="replies"/>

This configuration provides us with a number of beans. We configure our messaging middleware using ActiveMQ and inbound/outbound JMS adapters provided by Spring Integration. As shown, our itemWriter bean which is referenced by our job step utilizes the ChunkMessageChannelItemWriter for writing chunks over the configured middleware.

Now lets move on to the slave configuration:

  1. <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
  2. <property name="brokerURL" value="tcp://localhost:61616"/>
  3. </bean>
  4. <int:channel id="requests"/>
  5. <int:channel id="replies"/>
  6. <int-jms:message-driven-channel-adapter id="jmsIn"
  7. destination-name="requests"
  8. channel="requests"/>
  9. <int-jms:outbound-channel-adapter id="outgoingReplies"
  10. destination-name="replies"
  11. channel="replies">
  12. </int-jms:outbound-channel-adapter>
  13. <int:service-activator id="serviceActivator"
  14. input-channel="requests"
  15. output-channel="replies"
  16. ref="chunkProcessorChunkHandler"
  17. method="handleChunk"/>
  18. <bean id="chunkProcessorChunkHandler"
  19. class="org.springframework.batch.integration.chunk.ChunkProcessorChunkHandler">
  20. <property name="chunkProcessor">
  21. <bean class="org.springframework.batch.core.step.item.SimpleChunkProcessor">
  22. <property name="itemWriter">
  23. <bean class="io.spring.sbi.PersonItemWriter"/>
  24. </property>
  25. <property name="itemProcessor">
  26. <bean class="io.spring.sbi.PersonItemProcessor"/>
  27. </property>
  28. </bean>
  29. </property>
  30. </bean>

Most of these configuration items should look familiar from the master configuration. Slaves do not need access to things like the Spring Batch JobRepository nor access to the actual job configuration file. The main bean of interest is the “chunkProcessorChunkHandler”. The chunkProcessor property of ChunkProcessorChunkHandler takes a configured SimpleChunkProcessor which is where you would provide a reference to your ItemWriter and optionally your ItemProcessor that will run on the slave when it receives chunks from the master.

For more information, please also consult the Spring Batch manual, specifically the chapter on Remote Chunking.

Remote Partitioning

Spring Batch Integration模块 - 图4

Remote Partitioning, on the other hand, is useful when the problem is not the processing of items, but the associated I/O represents the bottleneck. Using Remote Partitioning, work can be farmed out to slaves that execute complete Spring Batch steps. Thus, each slave has its own ItemReader, ItemProcessor and ItemWriter. For this purpose, Spring Batch Integration provides the MessageChannelPartitionHandler.

This implementation of the PartitionHandler interface uses MessageChannel instances to send instructions to remote workers and receive their responses. This provides a nice abstraction from the transports (E.g. JMS or AMQP) being used to communicate with the remote workers.

The reference manual section Remote Partitioning provides an overview of the concepts and components needed to configure Remote Partitioning and shows an example of using the default TaskExecutorPartitionHandler to partition in separate local threads of execution. For Remote Partitioning to multiple JVM’s, two additional components are required:

  • Remoting fabric or grid environment
  • A PartitionHandler implementation that supports the desired remoting fabric or grid environment

Similar to Remote Chunking JMS can be used as the “remoting fabric” and the PartitionHandler implementation to be used as described above is the MessageChannelPartitionHandler. The example shown below assumes an existing partitioned job and focuses on the MessageChannelPartitionHandler and JMS configuration:

  1. <bean id="partitionHandler"
  2. class="org.springframework.batch.integration.partition.MessageChannelPartitionHandler">
  3. <property name="stepName" value="step1"/>
  4. <property name="gridSize" value="3"/>
  5. <property name="replyChannel" ref="outbound-replies"/>
  6. <property name="messagingOperations">
  7. <bean class="org.springframework.integration.core.MessagingTemplate">
  8. <property name="defaultChannel" ref="outbound-requests"/>
  9. <property name="receiveTimeout" value="100000"/>
  10. </bean>
  11. </property>
  12. </bean>
  13. <int:channel id="outbound-requests"/>
  14. <int-jms:outbound-channel-adapter destination="requestsQueue"
  15. channel="outbound-requests"/>
  16. <int:channel id="inbound-requests"/>
  17. <int-jms:message-driven-channel-adapter destination="requestsQueue"
  18. channel="inbound-requests"/>
  19. <bean id="stepExecutionRequestHandler"
  20. class="org.springframework.batch.integration.partition.StepExecutionRequestHandler">
  21. <property name="jobExplorer" ref="jobExplorer"/>
  22. <property name="stepLocator" ref="stepLocator"/>
  23. </bean>
  24. <int:service-activator ref="stepExecutionRequestHandler" input-channel="inbound-requests"
  25. output-channel="outbound-staging"/>
  26. <int:channel id="outbound-staging"/>
  27. <int-jms:outbound-channel-adapter destination="stagingQueue"
  28. channel="outbound-staging"/>
  29. <int:channel id="inbound-staging"/>
  30. <int-jms:message-driven-channel-adapter destination="stagingQueue"
  31. channel="inbound-staging"/>
  32. <int:aggregator ref="partitionHandler" input-channel="inbound-staging"
  33. output-channel="outbound-replies"/>
  34. <int:channel id="outbound-replies">
  35. <int:queue/>
  36. </int:channel>
  37. <bean id="stepLocator"
  38. class="org.springframework.batch.integration.partition.BeanFactoryStepLocator" />

Also ensure the partition handler attribute maps to the partitionHandler bean:

  1. <job id="personJob">
  2. <step id="step1.master">
  3. <partition partitioner="partitioner" handler="partitionHandler"/>
  4. ...
  5. </step>
  6. </job>