最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Spring Batch實現(xiàn)批處理任務的詳細教程

 更新時間:2024年06月30日 09:52:15   作者:E綿綿  
在企業(yè)級應用中,批處理任務是不可或缺的一部分,它們通常用于處理大量數(shù)據(jù),如數(shù)據(jù)遷移、數(shù)據(jù)清洗、生成報告等,Spring Batch是Spring框架的一部分,本文將介紹如何使用Spring Batch與SpringBoot結(jié)合,構(gòu)建和管理批處理任務,需要的朋友可以參考下

引言

在企業(yè)級應用中,批處理任務是不可或缺的一部分。它們通常用于處理大量數(shù)據(jù),如數(shù)據(jù)遷移、數(shù)據(jù)清洗、生成報告等。Spring Batch是Spring框架的一部分,專為批處理任務設(shè)計,提供了簡化的配置和強大的功能。本文將介紹如何使用Spring Batch與SpringBoot結(jié)合,構(gòu)建和管理批處理任務。

項目初始化

首先,我們需要創(chuàng)建一個SpringBoot項目,并添加Spring Batch相關(guān)的依賴項。可以通過Spring Initializr快速生成項目。

添加依賴

pom.xml中添加以下依賴:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-batch</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    <scope>runtime</scope>
</dependency>

配置Spring Batch

基本配置

Spring Batch需要一個數(shù)據(jù)庫來存儲批處理的元數(shù)據(jù)。我們可以使用HSQLDB作為內(nèi)存數(shù)據(jù)庫。配置文件application.properties

spring.datasource.url=jdbc:hsqldb:mem:testdb
spring.datasource.driverClassName=org.hsqldb.jdbc.JDBCDriver
spring.datasource.username=sa
spring.datasource.password=
spring.batch.initialize-schema=always

創(chuàng)建批處理任務

一個典型的Spring Batch任務包括三個主要部分:ItemReader、ItemProcessor和ItemWriter。

  • ItemReader:讀取數(shù)據(jù)的接口。
  • ItemProcessor:處理數(shù)據(jù)的接口。
  • ItemWriter:寫數(shù)據(jù)的接口。

創(chuàng)建示例實體類

創(chuàng)建一個示例實體類,用于演示批處理操作:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String firstName;
    private String lastName;

    // getters and setters
}

創(chuàng)建ItemReader

我們將使用一個簡單的FlatFileItemReader從CSV文件中讀取數(shù)據(jù):

import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.mapping.DelimitedLineTokenizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

@Configuration
public class BatchConfiguration {

    @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();
    }
}

創(chuàng)建ItemProcessor

創(chuàng)建一個簡單的ItemProcessor,將讀取的數(shù)據(jù)進行處理:

import org.springframework.batch.item.ItemProcessor;
import org.springframework.stereotype.Component;

@Component
public class PersonItemProcessor implements ItemProcessor<Person, Person> {

    @Override
    public Person process(Person person) throws Exception {
        final String firstName = person.getFirstName().toUpperCase();
        final String lastName = person.getLastName().toUpperCase();

        final Person transformedPerson = new Person();
        transformedPerson.setFirstName(firstName);
        transformedPerson.setLastName(lastName);

        return transformedPerson;
    }
}

創(chuàng)建ItemWriter

我們將使用一個簡單的JdbcBatchItemWriter將處理后的數(shù)據(jù)寫入數(shù)據(jù)庫:

import org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.batch.item.database.builder.JdbcBatchItemWriterBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

@Configuration
public class BatchConfiguration {

    @Bean
    public JdbcBatchItemWriter<Person> writer(NamedParameterJdbcTemplate jdbcTemplate) {
        return new JdbcBatchItemWriterBuilder<Person>()
                .itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>())
                .sql("INSERT INTO person (first_name, last_name) VALUES (:firstName, :lastName)")
                .dataSource(jdbcTemplate.getJdbcTemplate().getDataSource())
                .build();
    }
}

配置Job和Step

一個Job由多個Step組成,每個Step包含一個ItemReader、ItemProcessor和ItemWriter。

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableBatchProcessing
public class BatchConfiguration {

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Bean
    public Job importUserJob(JobCompletionNotificationListener listener, Step step1) {
        return jobBuilderFactory.get("importUserJob")
                .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();
    }
}

監(jiān)聽Job完成事件

創(chuàng)建一個監(jiān)聽器,用于監(jiān)聽Job完成事件:

import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.stereotype.Component;

@Component
public class JobCompletionNotificationListener implements JobExecutionListener {

    @Override
    public void beforeJob(JobExecution jobExecution) {
        System.out.println("Job Started");
    }

    @Override
    public void afterJob(JobExecution jobExecution) {
        System.out.println("Job Ended");
    }
}

測試與運行

創(chuàng)建一個簡單的CommandLineRunner,用于啟動批處理任務:

import org.springframework.batch.core.Job;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class BatchApplication implements CommandLineRunner {

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private Job job;

    public static void main(String[] args) {
        SpringApplication.run(BatchApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        jobLauncher.run(job, new JobParameters());
    }
}

在完成配置后,可以運行應用程序,并檢查控制臺輸出和數(shù)據(jù)庫中的數(shù)據(jù),確保批處理任務正常運行。

擴展功能

在基本的批處理任務基礎(chǔ)上,可以進一步擴展功能,使其更加完善和實用。例如:

  • 多步驟批處理:一個Job可以包含多個Step,每個Step可以有不同的ItemReader、ItemProcessor和ItemWriter。
  • 并行處理:通過配置多個線程或分布式處理,提升批處理任務的性能。
  • 錯誤處理和重試:配置錯誤處理和重試機制,提高批處理任務的可靠性。
  • 數(shù)據(jù)驗證:在處理數(shù)據(jù)前進行數(shù)據(jù)驗證,確保數(shù)據(jù)的正確性。

多步驟批處理

@Bean
public Job multiStepJob(JobCompletionNotificationListener listener, Step step1, Step step2) {
    return jobBuilderFactory.get("multiStepJob")
            .listener(listener)
            .start(step1)
            .next(step2)
            .end()
            .build();
}

@Bean
public Step step2(JdbcBatchItemWriter<Person> writer) {
    return stepBuilderFactory.get("step2")
            .<Person, Person>chunk(10)
            .reader(reader())
            .processor(processor())
            .writer(writer)
            .build();
}

并行處理

可以通過配置多個線程來實現(xiàn)并行處理:

@Bean
public Step step1(JdbcBatchItemWriter<Person> writer) {
    return stepBuilderFactory.get("step1")
            .<Person, Person>chunk(10)
            .reader(reader())
            .processor(processor())
            .writer(writer)
            .taskExecutor(taskExecutor())
            .build();
}

@Bean
public TaskExecutor taskExecutor() {
    SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();
    taskExecutor.setConcurrencyLimit(10);
    return taskExecutor;
}

結(jié)論

通過本文的介紹,我們了解了如何使用Spring Batch與SpringBoot結(jié)合,構(gòu)建和管理批處理任務。從項目初始化、配置Spring Batch、實現(xiàn)ItemReader、ItemProcessor和ItemWriter,到配置Job和Step,Spring Batch提供了一系列強大的工具和框架,幫助開發(fā)者高效地實現(xiàn)批處理任務。通過合理利用這些工具和框架,開發(fā)者可以構(gòu)建出高性能、可靠且易維護的批處理系統(tǒng)。希望這篇文章能夠幫助開發(fā)者更好地理解和使用Spring Batch,在實際項目中實現(xiàn)批處理任務的目標。

以上就是使用Spring Batch實現(xiàn)批處理任務的實例的詳細內(nèi)容,更多關(guān)于Spring Batch批處理任務的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • SpringBoot如何優(yōu)雅實現(xiàn)接口參數(shù)驗證

    SpringBoot如何優(yōu)雅實現(xiàn)接口參數(shù)驗證

    為了保證參數(shù)的正確性,我們需要使用參數(shù)驗證機制,來檢測并處理傳入的參數(shù)格式是否符合規(guī)范,所以本文就來和大家聊聊如何優(yōu)雅實現(xiàn)接口參數(shù)驗證吧
    2023-08-08
  • JAVA  字符串加密、密碼加密實現(xiàn)方法

    JAVA 字符串加密、密碼加密實現(xiàn)方法

    這篇文章主要介紹了JAVA 字符串加密、密碼加密實現(xiàn)方法的相關(guān)資料,需要的朋友可以參考下
    2016-10-10
  • 淺談springioc實例化bean的三個方法

    淺談springioc實例化bean的三個方法

    下面小編就為大家?guī)硪黄獪\談springioc實例化bean的三個方法。小編覺得挺不錯的,現(xiàn)在就想給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-09-09
  • java 中HashCode重復的可能性

    java 中HashCode重復的可能性

    這篇文章主要介紹了java 中HashCode重復的可能性的相關(guān)資料,這里提供實例及測試代碼,需要的朋友可以參考下
    2017-07-07
  • java環(huán)境中的JDK、JVM、JRE詳細介紹

    java環(huán)境中的JDK、JVM、JRE詳細介紹

    這篇文章主要介紹了java環(huán)境中的JDK、JVM、JRE詳細介紹的相關(guān)資料,對于初學者還是有必要了解下,細致說明他們是什么,需要的朋友可以參考下
    2016-11-11
  • Java語言的安裝、配置、編譯與運行過程

    Java語言的安裝、配置、編譯與運行過程

    本文詳細介紹了如何在Windows、macOS和Linux操作系統(tǒng)上安裝、配置Java開發(fā)環(huán)境(JDK),并展示了如何編寫、編譯和運行Java程序,同時,還提供了常見問題的解決方案,正確配置Java環(huán)境對Java開發(fā)至關(guān)重要,是進行Java編程的基礎(chǔ)
    2025-02-02
  • 從內(nèi)存模型中了解Java final的全部細節(jié)

    從內(nèi)存模型中了解Java final的全部細節(jié)

    關(guān)于final關(guān)鍵字,它也是我們一個經(jīng)常用的關(guān)鍵字,可以修飾在類上、或者修飾在變量、方法上,以此看來定義它的一些不可變性!像我們經(jīng)常使用的String類中,它便是final來修飾的類,并且它的字符數(shù)組也是被final所修飾的。但是一些final的一些細節(jié)你真的了解過嗎
    2022-03-03
  • SpringMVC 向jsp頁面?zhèn)鬟f數(shù)據(jù)庫讀取到的值方法

    SpringMVC 向jsp頁面?zhèn)鬟f數(shù)據(jù)庫讀取到的值方法

    下面小編就為大家分享一篇SpringMVC 向jsp頁面?zhèn)鬟f數(shù)據(jù)庫讀取到的值方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-03-03
  • 統(tǒng)一返回JsonResult踩坑的記錄

    統(tǒng)一返回JsonResult踩坑的記錄

    這篇文章主要介紹了統(tǒng)一返回JsonResult踩坑的記錄,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2025-06-06
  • Java編程實現(xiàn)排他鎖代碼詳解

    Java編程實現(xiàn)排他鎖代碼詳解

    這篇文章主要介紹了Java編程實現(xiàn)排他鎖的相關(guān)內(nèi)容,敘述了實現(xiàn)此代碼鎖所需要的功能,以及作者的解決方案,然后向大家分享了設(shè)計源碼,需要的朋友可以參考下。
    2017-10-10

最新評論

海淀区| 普格县| 交城县| 武穴市| 锡林郭勒盟| 广宗县| 泗阳县| 聂荣县| 龙陵县| 大关县| 宾阳县| 遂平县| 郸城县| 岱山县| 黑山县| 叶城县| 通江县| 古田县| 正镶白旗| 沙坪坝区| 太仓市| 渭南市| 开封县| 喀什市| 四川省| 武邑县| 浠水县| 佛教| 皮山县| 通山县| 岳普湖县| 横山县| 昔阳县| 浪卡子县| 阜阳市| 佛山市| 高阳县| 汤原县| 永兴县| 渭南市| 南和县|