zoukankan      html  css  js  c++  java
  • Spring Batch

    Spring Batch框架工作原理

    SpringBatch框架。它包含以下主要构建块

    一个 Batch(批处理)过程由一个 Job(作业)组成。这个实体封装了整个批处理过程。

    一个 Job(作业)可以由一个或多个 Step(步骤)组成。在大多数情况下,一个步骤将读取数据(通过 ItemReader),处理数据(使用 ItemProcessor),然后写入数据(通过 ItemWriter)。

    JobLauncher处理启动一个 Job(作业)。

    JobRepository存储关于配置和执行的 Job(作业)的元数据。

    示例

    pom依赖

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-batch</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.batch</groupId>
                <artifactId>spring-batch-test</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.15</version>
            </dependency>

    配置 Spring Batch Job

    创建一个 BatchConfig类,它将配置Spring Batch。类顶部的@Configuration注解表明Spring可以使用该类作为bean定义的源。

    我们添加了@EnableBatchProcessing注解,它支持所有所需 SpringBatch特性。它还提供了设置批处理作业的基本配置。

    通过添加这个注解会需要很多操作。下面是 @EnableBatchProcessing创建的概述:

    • JobRepository (bean名称 "jobRepository")

    • JobLauncher (bean名称 "jobLauncher")

    • JobRegistry (bean名称 "jobRegistry")

    • JobExplorer (bean名称 "jobExplorer")

    • PlatformTransactionManager (bean名称 "transactionManager")

    • JobBuilderFactory (bean名称"jobBuilders"),它可以方便地防止您必须将作业存储库注入到每个 Job(作业)中

    • StepBuilderFactory (bean名称 "stepBuilders"),以方便您避免将作业存储库和事务管理器注入到每个 Step(步骤)中

    为了使 SpringBatch使用基于Map的 JobRepository,我们需要扩展 DefaultBatchConfigurer。重写 setDataSource()方法以不设置 DataSource。这将导致自动配置使用基于Map的 JobRepository

    import org.springframework.batch.core.configuration.annotation.DefaultBatchConfigurer;
    import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @EnableBatchProcessing
    public class BatchConfig extends DefaultBatchConfigurer {
    
    }

    配置Hello World Spring Batch 作业

    @Configuration
    public class HelloWorldJobConfig {
    
        @Bean
        public Job helloWorlJob(JobBuilderFactory jobBuilders, StepBuilderFactory stepBuilders) {
            return jobBuilders.get("helloWorldJob").start(helloWorldStep(stepBuilders)).build();
        }
    
        @Bean
        public Step helloWorldStep(StepBuilderFactory stepBuilders) {
            return stepBuilders.get("helloWorldStep").<Person, String>chunk(10)
                    .reader(reader()).processor(processor()).writer(writer()).build();
        }
    
        @Bean
        public FlatFileItemReader<Person> reader() {
            return new FlatFileItemReaderBuilder<Person>().name("personItemReader")
                    .resource(new ClassPathResource("csv/persons.csv"))
                    .delimited().names(new String[]{"firstName", "lastName"}).targetType(Person.class).build();
        }
    
        @Bean
        public PersonItemProcessor processor() {
            return new PersonItemProcessor();
        }
    
        @Bean
        public FlatFileItemWriter<String> writer() {
            return new FlatFileItemWriterBuilder<String>().name("greetingItemWriter")
                    .resource(new FileSystemResource("txt/greetings.txt"))
                    .lineAggregator(new PassThroughLineAggregator<>()).build();
        }
    
    }

    处理数据

    public class PersonItemProcessor implements ItemProcessor<Person, String> {
    
    
        private static final Logger LOGGER = LoggerFactory.getLogger(PersonItemProcessor.class);
    
        @Override
        public String process(Person person) throws Exception {
            String greeting = "Hello " + person.getFirstName() + " " + person.getLastName() + "!";
            LOGGER.info("converting '{}' into '{}'", person, greeting);
            return greeting;
        }
    
    }

    测试Spring Batch 示例

    使用 @RunWith@SpringBootTest测试注解告诉 JUnit使用Spring的测试支持运行,并使用SpringBoot的支持引导。

    SpringBatch附带一个 JobLauncherTestUtils实用程序类,用于测试批处理作业。

    我们首先创建一个内部 BatchTestConfig类,将helloWorld作业添加到 JobLauncherTestUtils bean中。然后使用此bean的 launchJob()方法运行批处理作业。

    如果执行的作业没有任何错误,则 ExitCode的值为 COMPLETED

    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = {XcSpringbootApplicationTests.BatchTestConfig.class})
    public class XcSpringbootApplicationTests {
    
        @Autowired
        private JobLauncherTestUtils jobLauncherTestUtils;
    
        @Test
        public void testHelloWorldJob() throws Exception {
            JobExecution jobExecution = jobLauncherTestUtils.launchJob();
            assertThat(jobExecution.getExitStatus().getExitCode()).isEqualTo("COMPLETED");
        }
    
        @Configuration
        @Import({BatchConfig.class, HelloWorldJobConfig.class})
        static class BatchTestConfig {
    
            @Autowired
            private Job helloWorlJob;
    
            @Bean
            JobLauncherTestUtils jobLauncherTestUtils() throws NoSuchJobException {
                JobLauncherTestUtils jobLauncherTestUtils = new JobLauncherTestUtils();
                jobLauncherTestUtils.setJob(helloWorlJob);
                return jobLauncherTestUtils;
            }
    
        }
    }

    官网:https://spring.io/projects/spring-batch

    参考:https://codenotfound.com/spring-batch-example.html

    资料:https://www.jianshu.com/nb/39572085

  • 相关阅读:
    数据库目录
    设计模式
    mysql的索引结构
    ElasticSearch的基本操作
    转:基于Hadoop 的分布式网络爬虫技术学习笔记
    爬虫 es 搜索引擎
    vue+django2.0.2-rest-framework 生鲜项目
    fiddler抓包时显示Tunnel to......443
    安装 Win10 + Ubuntu 双系统过程
    ROS 订阅者的创建及使用
  • 原文地址:https://www.cnblogs.com/ooo0/p/15007618.html
Copyright © 2011-2022 走看看