自分でSpringBatchをビルドする
-
-
-
- 目標:
- ソースダウンロードアドレス
- 元の
- ビジネスデータはCVSファイル(sample-data.csv)に配置されます。
- SQLスクリプトは、データを格納するためのテーブル(schema-all.sql)を作成します。
- Spring BatchおよびHyperSQLデータベースの依存関係(pom.xml):
- 選択Gradle(build.gradle):
- ビジネスクラスを作成します。
- 中間プロセッサを作成します。
- バッチジョブの集計
- 上記のコードに関する詳細な説明:
- (JobCompletionNotificationListener.java):
- (BatchProcessingApplication.java):
- 実行
- 結果:
-
-
目標:
バッチジョブを作成します。CVSからデータをインポートし、変換してから、指定した場所に転送します。この例では、ログが印刷されます。
ソースダウンロードアドレス
元の
ビジネスデータはCVSファイル(sample-data.csv)に配置されます。
Jill,Doe
Joe,Doe
Justin,Doe
Jane,Doe
John,Doe
SQLスクリプトは、データを格納するためのテーブル(schema-all.sql)を作成します。
DROP TABLE people IF EXISTS;
CREATE TABLE people (
person_id BIGINT IDENTITY NOT NULL PRIMARY KEY,
first_name VARCHAR(20),
last_name VARCHAR(20)
);
Spring BatchおよびHyperSQLデータベースの依存関係(pom.xml):
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>batch-processing</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>batch-processing</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
選択Gradle(build.gradle):
plugins {
id 'org.springframework.boot' version '2.2.2.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-batch'
runtimeOnly 'org.hsqldb:hsqldb'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
testImplementation 'org.springframework.batch:spring-batch-test'
}
test {
useJUnitPlatform()
}
ビジネスクラスを作成します。
名と姓を使用して、コンストラクターを介して、またはプロパティを設定することにより、クラス(Person.java)をインスタンス化します。
package com.example.batchprocessing;
public class Person {
private String lastName;
private String firstName;
public Person() {
}
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "firstName: " + firstName + ", lastName: " + lastName;
}
}
中間プロセッサを作成します。
名前を大文字に変換するコンバーター(PersonItemProcessor.java):
package com.example.batchprocessing;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
public class PersonItemProcessor implements ItemProcessor<Person, Person> {
private static final Logger log = LoggerFactory.getLogger(PersonItemProcessor.class);
@Override
public Person process(final Person person) throws Exception {
final String firstName = person.getFirstName().toUpperCase();
final String lastName = person.getLastName().toUpperCase();
final Person transformedPerson = new Person(firstName, lastName);
log.info("Converting (" + person + ") into (" + transformedPerson + ")");
return transformedPerson;
}
}
バッチジョブの集計
リーダー、プロセッサー、ライター(BatchConfiguration.java):
@Configuration
@EnableBatchProcessing
public class BatchConfiguration {
@Autowired
public JobBuilderFactory jobBuilderFactory;
@Autowired
public StepBuilderFactory stepBuilderFactory;
// end::setup[]
// tag::readerwriterprocessor[]
@Bean
public FlatFileItemReader<Person> reader() {
return new FlatFileItemReaderBuilder<Person>()
.name("personItemReader")
.resource(new ClassPathResource("sample-data.csv"))
.delimited()
.names(new String[]{
"firstName", "lastName"})
.fieldSetMapper(new BeanWrapperFieldSetMapper<Person>() {
{
setTargetType(Person.class);
}})
.build();
}
@Bean
public PersonItemProcessor processor() {
return new PersonItemProcessor();
}
@Bean
public JdbcBatchItemWriter<Person> writer(DataSource dataSource) {
return new JdbcBatchItemWriterBuilder<Person>()
.itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>())
.sql("INSERT INTO people (first_name, last_name) VALUES (:firstName, :lastName)")
.dataSource(dataSource)
.build();
}
// end::readerwriterprocessor[]
// tag::jobstep[]
@Bean
public Job importUserJob(JobCompletionNotificationListener listener, Step step1) {
return jobBuilderFactory.get("importUserJob")
.incrementer(new RunIdIncrementer())
.listener(listener)
.flow(step1)
.end()
.build();
}
@Bean
public Step step1(JdbcBatchItemWriter<Person> writer) {
return stepBuilderFactory.get("step1")
.<Person, Person> chunk(10)
.reader(reader())
.processor(processor())
.writer(writer)
.build();
}
// end::jobstep[]
}
上記のコードに関する詳細な説明:
Spring Batchは多くのユーティリティクラスを提供し、カスタムコードを書く必要性を減らします。ビジネスロジックに集中できます。
コードの最初の部分は、入力、プロセッサ、および出力を定義します。
- reader()はItemReaderを作成します。sample-data.csvという名前のファイルを検索し、注文アイテムごとに十分な情報を解析して、Personに変換します。
- processor()は、データを大文字に変換するために、前に定義したPersonItemProcessorのインスタンスを作成します。
- ライター(データソース)はItemWriterを作成します。これはJDBCターゲット用であり、@ EnableBatchProcessingによって作成されたdataSourceのコピーを自動的に取得します。これには、JavaBeanプロパティによって駆動される単一のPersonを挿入するために必要なSQLステートメントが含まれています。
最初のメソッドはジョブを定義し、2番目のメソッドはステップを定義します。ジョブは段階的に構築され、各ステップに
は、リーダー、プロセッサ、およびライターのchunk()のプレフィックス<Person、Person>を含めることができ、各「チャンク」によって処理される入力と出力のタイプを示します。
ジョブが完了したときに通知を受け取る方法:
(JobCompletionNotificationListener.java):
package com.example.batchprocessing;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.listener.JobExecutionListenerSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@Component
public class JobCompletionNotificationListener extends JobExecutionListenerSupport {
private static final Logger log = LoggerFactory.getLogger(JobCompletionNotificationListener.class);
private final JdbcTemplate jdbcTemplate;
@Autowired
public JobCompletionNotificationListener(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public void afterJob(JobExecution jobExecution) {
if(jobExecution.getStatus() == BatchStatus.COMPLETED) {
log.info("!!! JOB FINISHED! Time to verify the results");
jdbcTemplate.query("SELECT first_name, last_name FROM people",
(rs, row) -> new Person(
rs.getString(1),
rs.getString(2))
).forEach(person -> log.info("Found <" + person + "> in the database."));
}
}
}
(BatchProcessingApplication.java):
package com.example.batchprocessing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BatchProcessingApplication {
public static void main(String[] args) throws Exception {
System.exit(SpringApplication.exit(SpringApplication.run(BatchProcessingApplication.class, args)));
}
}
@SpringBootApplicationは、次のすべてを追加する便利なアノテーションです。
- @Configuration:クラスをアプリケーションコンテキストのBean定義のソースとしてマークします。
- @EnableAutoConfiguration:クラスパス設定、他のBean、およびさまざまなプロパティ設定に基づいてBeanの追加を開始するようにSpringBootに指示します。たとえば、spring-webmvcがクラスパス上にある場合、このアノテーションはアプリケーションをWebアプリケーションとしてマークし、DispatcherServletの設定などの主要な動作をアクティブにします。
- @ComponentScan:Springに、パッケージ内の他のコンポーネントを探し、com / exampleを構成して提供し、コントローラーを見つけさせるように指示します。
実行
- 2つのMavenファイルを右クリックして以下を選択します。
- 起動:
- Mavenで、完全なファイルに対応するjarパッケージを入力します:(判断方法は、jarが最終的に完全なフォルダーにあることです)
-execute java -jar target / jarパッケージ名(java -jar target /batch-processing-0.0。 1.jar)
結果:
ログに出力された実行結果を確認し、名前をすべて大文字に変換できます。