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

使用Spring Batch實(shí)現(xiàn)批處理任務(wù)的詳細(xì)教程

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

引言

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

項(xiàng)目初始化

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

添加依賴

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需要一個(gè)數(shù)據(jù)庫(kù)來(lái)存儲(chǔ)批處理的元數(shù)據(jù)。我們可以使用HSQLDB作為內(nèi)存數(shù)據(jù)庫(kù)。配置文件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)建批處理任務(wù)

一個(gè)典型的Spring Batch任務(wù)包括三個(gè)主要部分:ItemReader、ItemProcessor和ItemWriter。

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

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

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

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

我們將使用一個(gè)簡(jiǎn)單的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)建一個(gè)簡(jiǎn)單的ItemProcessor,將讀取的數(shù)據(jù)進(jìn)行處理:

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

我們將使用一個(gè)簡(jiǎn)單的JdbcBatchItemWriter將處理后的數(shù)據(jù)寫(xiě)入數(shù)據(jù)庫(kù):

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

一個(gè)Job由多個(gè)Step組成,每個(gè)Step包含一個(gè)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)聽(tīng)Job完成事件

創(chuàng)建一個(gè)監(jiān)聽(tīng)器,用于監(jiān)聽(tīng)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");
    }
}

測(cè)試與運(yùn)行

創(chuàng)建一個(gè)簡(jiǎn)單的CommandLineRunner,用于啟動(dòng)批處理任務(wù):

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

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

擴(kuò)展功能

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

  • 多步驟批處理:一個(gè)Job可以包含多個(gè)Step,每個(gè)Step可以有不同的ItemReader、ItemProcessor和ItemWriter。
  • 并行處理:通過(guò)配置多個(gè)線程或分布式處理,提升批處理任務(wù)的性能。
  • 錯(cuò)誤處理和重試:配置錯(cuò)誤處理和重試機(jī)制,提高批處理任務(wù)的可靠性。
  • 數(shù)據(jù)驗(yàn)證:在處理數(shù)據(jù)前進(jìn)行數(shù)據(jù)驗(yàn)證,確保數(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();
}

并行處理

可以通過(guò)配置多個(gè)線程來(lái)實(shí)現(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é)論

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

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

相關(guān)文章

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

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

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

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

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

    淺談springioc實(shí)例化bean的三個(gè)方法

    下面小編就為大家?guī)?lái)一篇淺談springioc實(shí)例化bean的三個(gè)方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就想給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-09-09
  • java 中HashCode重復(fù)的可能性

    java 中HashCode重復(fù)的可能性

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

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

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

    Java語(yǔ)言的安裝、配置、編譯與運(yùn)行過(guò)程

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

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

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

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

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

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

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

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

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

最新評(píng)論

金坛市| 宜兴市| 东乌珠穆沁旗| 东平县| 当涂县| 定南县| 青田县| 洪雅县| 珠海市| 石首市| 神池县| 蒙自县| 防城港市| 天门市| 文化| 寻甸| 南木林县| 保康县| 西畴县| 繁峙县| 山东省| 阿坝| 栾城县| 双牌县| 三原县| 苍山县| 金昌市| 成安县| 和平区| 通州区| 石家庄市| 久治县| 理塘县| 湖南省| 平昌县| 湘西| 余干县| 来宾市| 郑州市| 额尔古纳市| 仁化县|