[Spring Batchシリーズ]第1節Spring Batchの初認識
64414 ワード
Spring Batchを使い始めてからしばらく経って、ずっと整理する時間がなくて、今プロジェクトはもうすぐ終わります.この時間の勉強と使用経験を整理します.
公式サイトアドレス:http://projects.spring.io/spring-batch/
一、定義と特徴
A lightweight, comprehensive batch framework designed to enable the development of robust batch applications vital for the daily operations of enterprise systems.
Spring Batch provides reusable functions that are essential in processing large volumes of records, including logging/tracing, transaction management, job processing statistics, job restart, skip, and resource management. It also provides more advanced technical services and features that will enable extremely high-volume and high performance batch jobs through optimization and partitioning techniques. Simple as well as complex, high-volume batch jobs can leverage the framework in a highly scalable manner to process significant volumes of information.
Features Transaction management Chunk based processing Declarative I/O Start/Stop/Restart Rety/Skip Web based administration interface (Spring Batch Admin)
二、紹介
Spring BatchはSpringに頼り、バッチ向けのフレームワークであり、エンタープライズクラスのデータ処理システムに応用できる.公式サイトのドキュメントを読むと、Spring BatchのコアコンポーネントにはJob、Stepなどが含まれていることがわかります.Spring Batchは統一的な読み書きインターフェース、豊富なタスク処理方式、柔軟な事務管理と同時処理を提供するだけでなく、同時にログ、監視、タスクの再起動とスキップなどの特性をサポートし、バッチ処理応用開発を大幅に簡素化し、開発者を複雑なタスク配置管理過程から解放した.コアのビジネス処理プロセスにもっと注目することができます.
シーンの操作 Commit batch process periodically Concurrent batch processing: parallel processing of a job Staged, enterprise message-driven processing Massively parallel batch processing Manual or scheduled restart after failure Sequential processing of dependent steps (with extensions to workflow-driven batches) Partial processing: skip records (e.g. on rollback) Whole-batch transaction: for cases with a small batch size or existing stored procedures/scripts
三、HelloWorld
プログラム概要:指定したパスのテキストファイルから行ごとに読み取り、ユーザーの姓と名前を取得し、プロセッサでユーザーの名前をつなぎ、最後にユーザーの名前を出力します.
OS:Win 7 x 64フラッグシップ
開発環境:Eclipse 4.3、JDK 1.6
手順:
1.構築開発工程
Eclipseを開き、Java Projectを新規作成します.この例ではSpringBatchTestをプロジェクト名として使用します.
新しいlibフォルダを作成し、SpringBatchのJarパッケージとその他の依存パッケージをインポートします.関連パッケージとclassを作成し、次の図のような構造を得ます.
パッケージとクラス定義:
accアクセス制御クラスの格納(この例ではジョブテストクラスの格納の準備)
batch.Listenerバッチリスナーの保存
batch.プロセスストレージItemProcessor実装クラス
batch.reader ItemReaderインプリメンテーションクラスの保存
batch.writer ItemWriter実装クラスの格納
batch.mapperは論理オブジェクトマッピング処理クラスを格納する(この例ではテキスト行をテキスト行オブジェクトマッピング処理クラスに格納する準備をする)
batch.dataバッチ処理で使用される論理オブジェクトの格納
BatchServer.JAvaバッチタスクメソッドインタフェースの定義
プロファイル定義:
spring-application-batch.xml spring batchコアコンポーネントとカスタムジョブの定義
spring-application-resource.xml定義springコンポーネント
spring-application-context.xmlルートプロファイル、使用するプロファイルを導入し、プロファイルの導入順序を制御
2.プロファイルと対応するプログラムコードの作成
開発中、プロファイルとプログラムは並行して書かれているため、以下の内容には特定の順序がありません.
(1)Spring Batchプロファイルおよび定義されたコンポーネントインスタンス
spring-application-batch.xml
この例ではSpring Batchが提供する固定長テキストローディングインスタンス(FlatFileItemReader)を使用するため、Readerはカスタマイズされていません.
LineVo.java
View Code
CustomLineMapper.java
View Code
CustomProcessor.java
View Code
CustomWriter.java
View Code
CustomJobListener.JAvaとCustomStep Listener.JAvaこの例では空の定義のみが与えられます.
BatchServer.java
View Code
(2)accパッケージの下に新しいテストクラスMainTestを作成する.JAvaはIディスクにSpringBatchTestを新規作成します.txt
View Code
View Code
以上の手順により、projectディレクトリ構造は以下の図になります.
3.これでHelloWorldプロジェクト全体の構築が完了し、プログラムを実行することができ、出力結果は以下の通りである.
View Code
まとめ:Spring BatchとSpring Batchを用いたHelloWorldプログラムの開発について簡単に紹介します.
本明細書でProjectソースコードを使用して、ここからダウンロードできます:http://download.csdn.net/detail/driftingshine/8194729
公式サイトアドレス:http://projects.spring.io/spring-batch/
一、定義と特徴
A lightweight, comprehensive batch framework designed to enable the development of robust batch applications vital for the daily operations of enterprise systems.
Spring Batch provides reusable functions that are essential in processing large volumes of records, including logging/tracing, transaction management, job processing statistics, job restart, skip, and resource management. It also provides more advanced technical services and features that will enable extremely high-volume and high performance batch jobs through optimization and partitioning techniques. Simple as well as complex, high-volume batch jobs can leverage the framework in a highly scalable manner to process significant volumes of information.
Features
二、紹介
Spring BatchはSpringに頼り、バッチ向けのフレームワークであり、エンタープライズクラスのデータ処理システムに応用できる.公式サイトのドキュメントを読むと、Spring BatchのコアコンポーネントにはJob、Stepなどが含まれていることがわかります.Spring Batchは統一的な読み書きインターフェース、豊富なタスク処理方式、柔軟な事務管理と同時処理を提供するだけでなく、同時にログ、監視、タスクの再起動とスキップなどの特性をサポートし、バッチ処理応用開発を大幅に簡素化し、開発者を複雑なタスク配置管理過程から解放した.コアのビジネス処理プロセスにもっと注目することができます.
シーンの操作
三、HelloWorld
プログラム概要:指定したパスのテキストファイルから行ごとに読み取り、ユーザーの姓と名前を取得し、プロセッサでユーザーの名前をつなぎ、最後にユーザーの名前を出力します.
OS:Win 7 x 64フラッグシップ
開発環境:Eclipse 4.3、JDK 1.6
手順:
1.構築開発工程
Eclipseを開き、Java Projectを新規作成します.この例ではSpringBatchTestをプロジェクト名として使用します.
新しいlibフォルダを作成し、SpringBatchのJarパッケージとその他の依存パッケージをインポートします.関連パッケージとclassを作成し、次の図のような構造を得ます.
パッケージとクラス定義:
accアクセス制御クラスの格納(この例ではジョブテストクラスの格納の準備)
batch.Listenerバッチリスナーの保存
batch.プロセスストレージItemProcessor実装クラス
batch.reader ItemReaderインプリメンテーションクラスの保存
batch.writer ItemWriter実装クラスの格納
batch.mapperは論理オブジェクトマッピング処理クラスを格納する(この例ではテキスト行をテキスト行オブジェクトマッピング処理クラスに格納する準備をする)
batch.dataバッチ処理で使用される論理オブジェクトの格納
BatchServer.JAvaバッチタスクメソッドインタフェースの定義
プロファイル定義:
spring-application-batch.xml spring batchコアコンポーネントとカスタムジョブの定義
spring-application-resource.xml定義springコンポーネント
spring-application-context.xmlルートプロファイル、使用するプロファイルを導入し、プロファイルの導入順序を制御
2.プロファイルと対応するプログラムコードの作成
開発中、プロファイルとプログラムは並行して書かれているため、以下の内容には特定の順序がありません.
(1)Spring Batchプロファイルおよび定義されたコンポーネントインスタンス
spring-application-batch.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:batch="http://www.springframework.org/schema/batch"
4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5 xsi:schemaLocation="http://www.springframework.org/schema/beans
6 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
7 http://www.springframework.org/schema/batch
8 http://www.springframework.org/schema/batch/spring-batch-2.2.xsd"
9 default-autowire="byName">
10
11 <!-- Spring Batch -->
12 <bean id="jobRepository" class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean" />
13 <bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
14 <property name="jobRepository" ref="jobRepository" />
15 </bean>
16 <bean id="taskExecutor" class="org.springframework.core.task.SyncTaskExecutor" />
17
18
19 <!-- -->
20 <bean id="customerLineMapper" class="cn.spads.batch.mapper.CustomLineMapper"/>
21 <bean id="lineTokenizer" class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer" >
22 <property name="delimiter" value=" "/>
23 </bean>
24
25 <!-- Scope = step , -->
26 <bean id="customReader" class="org.springframework.batch.item.file.FlatFileItemReader" scope="step">
27 <property name="lineMapper">
28 <bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
29 <property name="lineTokenizer" ref="lineTokenizer"/>
30 <property name="fieldSetMapper" ref="customerLineMapper"/>
31 </bean>
32 </property>
33 <!-- -->
34 <property name="resource" value="file:#{jobParameters['customFileAbPath']}"/>
35 </bean>
36
37 <bean id="customProcessor" class="cn.spads.batch.processor.CustomProcessor"/>
38 <bean id="customWriter" class="cn.spads.batch.writer.CustomWriter"/>
39
40 <bean id="customJobListener" class="cn.spads.batch.listener.CustomJobListener"/>
41 <bean id="customStepListener" class="cn.spads.batch.listener.CustomStepListener"/>
42
43
44 <batch:job id="customJob">
45 <batch:step id="customJob_first_step">
46 <batch:tasklet>
47 <batch:chunk reader="customReader" processor="customProcessor"
48 writer="customWriter" commit-interval="100">
49 </batch:chunk>
50 <batch:listeners>
51 <batch:listener ref="customStepListener" />
52 </batch:listeners>
53 </batch:tasklet>
54 </batch:step>
55 <batch:listeners>
56 <batch:listener ref="customJobListener"/>
57 </batch:listeners>
58 </batch:job>
59 </beans>
この例ではSpring Batchが提供する固定長テキストローディングインスタンス(FlatFileItemReader)を使用するため、Readerはカスタマイズされていません.
LineVo.java
package cn.spads.batch.data;
/**
* <b> </b><br>
* @author Gaylen
* @version V1.1.0
* history
* 1.1.0, 2014 11 24 Gaylen FE
* @since Java 6.0
*/
public class LineVo {
/** */
private int id;
/** */
private String givenName;
/** */
private String familyName;
/** */
private String fullName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
}
View Code
CustomLineMapper.java
package cn.spads.batch.mapper;
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.validation.BindException;
import cn.spads.batch.data.LineVo;
/**
* <b> - </b><br>
* @author Gaylen
* @version V1.1.0
* history
* 1.1.0, 2014-11-24 Gaylen FE
* @since Java 6.0
*/
public class CustomLineMapper implements FieldSetMapper<LineVo> {
/**
* <b> </b><br>
* @param fieldSet
* @return DelCommandBean
*/
@Override
public LineVo mapFieldSet(FieldSet fieldSet) throws BindException {
LineVo lv = new LineVo();
lv.setId(Integer.parseInt(fieldSet.readString(0)));
lv.setGivenName(fieldSet.readString(1));
lv.setFamilyName(fieldSet.readString(2));
return lv;
}
}
View Code
CustomProcessor.java
package cn.spads.batch.processor;
import org.springframework.batch.item.ItemProcessor;
import cn.spads.batch.data.LineVo;
/**
* <b> </b><br>
* @author Gaylen
* @version V1.1.0
* history
* 1.1.0, 2014 11 24 Gaylen FE
* @since Java 6.0
*/
public class CustomProcessor implements ItemProcessor<LineVo, LineVo> {
@Override
public LineVo process(LineVo item) throws Exception {
if (item == null) {
return null;
}
item.setFullName(new StringBuilder().append(item.getFamilyName() == null ? "*" : item.getFamilyName())
.append(" - ")
.append(item.getGivenName() == null ? "*" : item.getGivenName())
.toString());
return item;
}
}
View Code
CustomWriter.java
package cn.spads.batch.writer;
import java.util.List;
import org.springframework.batch.item.ItemWriter;
import cn.spads.batch.data.LineVo;
/**
* <b> </b><br>
* @author Gaylen
* @version V1.1.0
* history
* 1.1.0, 2014 11 24 Gaylen FE
* @since Java 6.0
*/
public class CustomWriter implements ItemWriter<LineVo> {
@Override
public void write(List<? extends LineVo> items) throws Exception {
if (items == null || items.size() == 0) {
System.out.println("error.");
} else {
for (LineVo lv : items) {
System.out.println(lv.getFullName());
}
}
}
}
View Code
CustomJobListener.JAvaとCustomStep Listener.JAvaこの例では空の定義のみが与えられます.
BatchServer.java
package cn.spads.batch;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameter;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
/**
* <b> </b><br>
* @author Gaylen
* @version V1.1.0
* history
* 1.1.0, 2014 11 24 Gaylen FE
* @since Java 6.0
*/
public class BatchServer {
/** */
private static final BatchServer INSTANCE = new BatchServer();
/**
*
* @return
*/
public static BatchServer getInstance() {
return INSTANCE;
}
/**
*
*/
private BatchServer() {
}
/**
* <b> </b><br>
* @param launcher
* @param job
* @param paraMap
*/
public void execCustomJob(JobLauncher launcher, Job job, Map<String, Object> paraMap) {
JobExecution result = this.executeBatchJob(launcher, job, this.getJobParameters(paraMap));
System.out.println(result.toString());
}
/**
* <b> </b><br>
*
* @param paraMap
* @return
*/
private JobParameters getJobParameters(Map<String, Object> paraMap) {
HashMap<String, JobParameter> parameters = new HashMap<String, JobParameter>();
parameters.put("time", new JobParameter(Calendar.getInstance().getTimeInMillis()));
String key = null;
Object value = null;
if (paraMap == null || paraMap.size() == 0) {
return new JobParameters(parameters);
}
for (Entry<String, Object> entry : paraMap.entrySet()) {
if (entry == null) {
continue;
}
key = entry.getKey();
value = entry.getValue();
if (value instanceof Date) {
parameters.put(key, new JobParameter((Date) value));
} else if (value instanceof String || value instanceof Integer) {
parameters.put(key, new JobParameter((String) value));
} else if (value instanceof Double) {
parameters.put(key, new JobParameter((Double) value));
} else if (value instanceof Long) {
parameters.put(key, new JobParameter((Long) value));
}
}
return new JobParameters(parameters);
}
/**
* <b> </b><br>
* @param joblanuncher
* @param job
* @param parameters
*/
public JobExecution executeBatchJob(JobLauncher launcher, Job job, JobParameters jobParameters) {
JobExecution result = null;
try {
result = launcher.run(job, jobParameters);
} catch (JobExecutionAlreadyRunningException e) {
e.printStackTrace();
} catch (JobRestartException e) {
e.printStackTrace();
} catch (JobInstanceAlreadyCompleteException e) {
e.printStackTrace();
} catch (JobParametersInvalidException e) {
e.printStackTrace();
}
return result;
}
}
View Code
(2)accパッケージの下に新しいテストクラスMainTestを作成する.JAvaはIディスクにSpringBatchTestを新規作成します.txt
package cn.spads.acc;
import java.util.HashMap;
import java.util.Map;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import cn.spads.batch.BatchServer;
/**
* <b> </b><br>
* @author Gaylen
* @version V1.1.0
* history
* 1.1.0, 2014 11 24 Gaylen FE
* @since Java 6.0
*/
public class MainTest {
static private String fileLocation = "I:/SpringBatchTest.txt";
static private void testCustomJob(ApplicationContext context) {
JobLauncher launcher = (JobLauncher) context.getBean("jobLauncher");
Job job = (Job) context.getBean("customJob");
Map<String, Object> paraMap = new HashMap<String, Object>();
paraMap.put("customFileAbPath", fileLocation);
BatchServer.getInstance().execCustomJob(launcher, job, paraMap);
}
public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext("config/spring-application-context.xml");
testCustomJob(context);
}
}
View Code
(SpringBatchTest.txt) :
1
2
3
4
View Code
以上の手順により、projectディレクトリ構造は以下の図になります.
3.これでHelloWorldプロジェクト全体の構築が完了し、プログラムを実行することができ、出力結果は以下の通りである.
1 2014-11-25 0:12:28 org.springframework.context.support.FileSystemXmlApplicationContext prepareRefresh
2 : Refreshing org.springframework.context.support.FileSystemXmlApplicationContext@bf32c: startup date [Tue Nov 25 00:12:28 CST 2014]; root of context hierarchy
3 2014-11-25 0:12:28 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
4 : Loading XML bean definitions from file [D:\LocalDEV\workspace43\SpringBatchTest\config\spring-application-context.xml]
5 2014-11-25 0:12:28 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
6 : Loading XML bean definitions from file [D:\LocalDEV\workspace43\SpringBatchTest\config\spring-application-resource.xml]
7 2014-11-25 0:12:28 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
8 : Loading XML bean definitions from file [D:\LocalDEV\workspace43\SpringBatchTest\config\spring-application-batch.xml]
9 2014-11-25 0:12:28 org.springframework.beans.factory.support.DefaultListableBeanFactory registerBeanDefinition
10 : Overriding bean definition for bean 'customJob': replacing [Generic bean: class [org.springframework.batch.core.configuration.xml.SimpleFlowFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Generic bean: class [org.springframework.batch.core.configuration.xml.JobParserJobFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
11 2014-11-25 0:12:28 org.springframework.beans.factory.support.DefaultListableBeanFactory registerBeanDefinition
12 : Overriding bean definition for bean 'customReader': replacing [Generic bean: class [org.springframework.batch.item.file.FlatFileItemReader]; scope=step; abstract=false; lazyInit=false; autowireMode=1; dependencyCheck=0; autowireCandidate=false; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\LocalDEV\workspace43\SpringBatchTest\config\spring-application-batch.xml]] with [Root bean: class [org.springframework.aop.scope.ScopedProxyFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in BeanDefinition defined in file [D:\LocalDEV\workspace43\SpringBatchTest\config\spring-application-batch.xml]]
13 2014-11-25 0:12:28 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
14 : Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@157fb52: defining beans [transactionManager,jobRepository,jobLauncher,taskExecutor,customerLineMapper,lineTokenizer,customReader,customProcessor,customWriter,customJobListener,customStepListener,org.springframework.batch.core.scope.internalStepScope,org.springframework.beans.factory.config.CustomEditorConfigurer,org.springframework.batch.core.configuration.xml.CoreNamespacePostProcessor,customJob_first_step,customJob,scopedTarget.customReader]; root of factory hierarchy
15 2014-11-25 0:12:28 org.springframework.batch.core.launch.support.SimpleJobLauncher run
16 : Job: [FlowJob: [name=customJob]] launched with the following parameters: [{time=1416845548796, customFileAbPath=I:/SpringBatchTest.txt}]
17 2014-11-25 0:12:28 org.springframework.batch.core.job.SimpleStepHandler handleStep
18 : Executing step: [customJob_first_step]
19 -
20 -
21 -
22 -
23 2014-11-25 0:12:28 org.springframework.batch.core.launch.support.SimpleJobLauncher run
24 : Job: [FlowJob: [name=customJob]] completed with the following parameters: [{time=1416845548796, customFileAbPath=I:/SpringBatchTest.txt}] and the following status: [COMPLETED]
25 JobExecution: id=0, version=2, startTime=Tue Nov 25 00:12:28 CST 2014, endTime=Tue Nov 25 00:12:28 CST 2014, lastUpdated=Tue Nov 25 00:12:28 CST 2014, status=COMPLETED, exitStatus=exitCode=COMPLETED;exitDescription=, job=[JobInstance: id=0, version=0, Job=[customJob]], jobParameters=[{time=1416845548796, customFileAbPath=I:/SpringBatchTest.txt}]
View Code
まとめ:Spring BatchとSpring Batchを用いたHelloWorldプログラムの開発について簡単に紹介します.
本明細書でProjectソースコードを使用して、ここからダウンロードできます:http://download.csdn.net/detail/driftingshine/8194729