`
weiqingfei
  • 浏览: 315357 次
  • 性别: Icon_minigender_1
  • 来自: 黑洞
社区版块
存档分类
最新评论

Spring batch的自动运行

    博客分类:
  • Java
阅读更多

一个最简单的spring batch的程序,照办官网的sample,如下

一个配置程序

 

@Configuration
@EnableBatchProcessing
@EnableAutoConfiguration
public class BatchConfiguration {

  @Autowired
  private JobBuilderFactory jobBuilderFactory;

  @Autowired
  private StepBuilderFactory stepBuilderFactory;

  @Bean
  public Step step1() {
    return stepBuilderFactory.get("step1")
        .tasklet(new Tasklet() {
          public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) {
            return null;
          }
        })
        .build();
  }

  @Bean
  public Job job(Step step1) throws Exception {
    return jobBuilderFactory.get("job1")
        .incrementer(new RunIdIncrementer())
        .start(step1)
        .build();
  }
}

 

 

 一个主程序

 

public class Main {
  public static void main(String [] args) {
    System.exit(SpringApplication.exit(SpringApplication.run(
        BatchConfiguration.class, args)));
  }
}

 你肯定会好奇,为啥Job就执行了呢?没看到调用啊

 

实际上在Spring batch的配置程序org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration里有以下代码

 

	@Bean
	@ConditionalOnMissingBean
	@ConditionalOnProperty(prefix = "spring.batch.job", name = "enabled", havingValue = "true", matchIfMissing = true)
	public JobLauncherCommandLineRunner jobLauncherCommandLineRunner(
			JobLauncher jobLauncher, JobExplorer jobExplorer) {
		JobLauncherCommandLineRunner runner = new JobLauncherCommandLineRunner(
				jobLauncher, jobExplorer);
		String jobNames = this.properties.getJob().getNames();
		if (StringUtils.hasText(jobNames)) {
			runner.setJobNames(jobNames);
		}
		return runner;
	}

 

 

也就是当配置文件里定义spring.batch.job.enabled为true,或者没定义(默认为true)的时候,会初始化一个JobLauncherCommandLineRunner的bean。

而在SpringApplication里有以下代码

 

	private void callRunners(ApplicationContext context, ApplicationArguments args) {
		List<Object> runners = new ArrayList<Object>();
		runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
		runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
		AnnotationAwareOrderComparator.sort(runners);
		for (Object runner : new LinkedHashSet<Object>(runners)) {
			if (runner instanceof ApplicationRunner) {
				callRunner((ApplicationRunner) runner, args);
			}
			if (runner instanceof CommandLineRunner) {
				callRunner((CommandLineRunner) runner, args);
			}
		}
	}

 也就是只要能找到ApplicationRunner或者CommandLineRunner的子类,就挨个执行。

 

默认是没有ApplicationRunner的子类的,而CommandLineRunner得子类就是JobLauncherCommandLineRunner了,所以会执行所配置的job。

如果想自己执行job的话,使用以下代码便可。

 

	@Autowired
	private JobLauncher jobLauncher;
	@Autowired
	private Job job;
	
	@Scheduled(initialDelay=3000,fixedRate = 1000)
	public void run(){
		try {
			JobExecution execution = jobLauncher.run(job, new JobParameters());
			System.out.println("Execution status: "+ execution.getStatus());
		} catch (JobExecutionAlreadyRunningException | JobRestartException | JobInstanceAlreadyCompleteException
				| JobParametersInvalidException e) {
			e.printStackTrace();
		} 
	}

 这时候,你可能会好奇,JobLauncher是哪儿配置的?

 

上面的配置文件里使用了注解@EnableBatchProcessing

这个注解会初始化以下所有bean

 

写道

 

JobRepository bean 名称 "jobRepository"
JobLauncher bean名称"jobLauncher"
JobRegistry bean名称"jobRegistry"
PlatformTransactionManager bean名称 "transactionManager"
JobBuilderFactory bean名称"jobBuilders"
StepBuilderFactory bean名称"stepBuilders"

 在程序org.springframework.batch.core.configuration.annotation.BatchConfigurationSelector会根据定义选择配置程序,默认用的是SimpleBatchConfiguration

 

public class BatchConfigurationSelector implements ImportSelector {

	@Override
	public String[] selectImports(AnnotationMetadata importingClassMetadata) {
		Class<?> annotationType = EnableBatchProcessing.class;
		AnnotationAttributes attributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(
				annotationType.getName(), false));
		Assert.notNull(attributes, String.format("@%s is not present on importing class '%s' as expected",
				annotationType.getSimpleName(), importingClassMetadata.getClassName()));

		String[] imports;
		if (attributes.containsKey("modular") && attributes.getBoolean("modular")) {
			imports = new String[] { ModularBatchConfiguration.class.getName() };
		}
		else {
			imports = new String[] { SimpleBatchConfiguration.class.getName() };
		}

		return imports;
	}

}

 

分享到:
评论
1 楼 zsf513 2017-09-22  
怒赞       

相关推荐

    Spring Boot整合Spring Batch,实现批处理

    通过自动配置和“起步依赖”(Starter Dependency),Spring Boot使得创建独立的、生产级别的Java应用变得简单。对于批处理场景,Spring Boot可以轻松配置数据库连接、日志记录、应用监控等基础设施。 其次,**...

    quartz整合springbatch动态集群定时实现mysql参考

    在这个“quartz_springbatch_dynamic”项目中,我们将看到如何将这两个强大的工具结合起来,以实现动态集群环境中的定时任务执行,并使用MySQL作为数据存储。 Quartz是一个开源的作业调度框架,允许开发者创建、...

    Spring Batch批处理框架

    Spring Batch提供了强大的错误处理机制,比如可以配置当ItemReader读取失败时,作业会自动重试,或当ItemProcessor处理出错时,可以跳过当前项继续处理下一项。这些机制极大地提高了批处理作业的健壮性。 5. 作业...

    springBoot+springBatch批量处理数据demo

    在`pom.xml`或`build.gradle`文件中添加依赖后,SpringBoot会自动加载SpringBatch的配置。 接着,SpringBatch的主要组件包括Job、Step、Tasklet、ItemReader、ItemWriter和ItemProcessor。Job是批处理任务的高层次...

    Spring Batch 参考文档中文版

    Spring Batch的使用场景主要集中在需要定时执行的复杂业务规则处理、以及海量数据的自动业务逻辑处理。这类批处理作业通常需要极高的效率且不需要人工干预,常见的包括月末统计、账单处理、保险赔款计算等。 Spring...

    spring batch

    Spring Batch 是一个强大的、全面的批处理框架,用于处理大量数据。...通过 `springbatchdemo` 和 `springbatch` 文件,开发者可以深入学习如何配置和使用 Spring Batch 来处理复杂的批量数据处理任务。

    springbatch简单用

    9. **事务管理(Transaction Management)**:SpringBatch 自动管理事务,确保在处理大量数据时的数据一致性。如果在步骤中发生错误,事务会被回滚,防止数据损坏。 10. **分片与并行执行(Splitting & Parallel ...

    spring batch demo

    4. **事务管理**:Spring Batch 自动管理批处理操作的事务,确保处理的数据一致性。即使在处理过程中出现错误,也能通过回滚事务来恢复到一致状态。 5. **作业与步骤**:Spring Batch中的“作业”(Job)是批处理...

    ElasticJob与SpringBatch的结合使用

    ### ElasticJob与SpringBatch的结合使用 #### 一、引言 随着大数据和微服务架构的兴起,数据处理的需求越来越复杂。在很多场景下,我们需要处理海量数据,并且要保证数据处理的一致性和顺序性。为此,业界发展出了...

    【SpringBatch】批处理框架整合配置过程文档.docx

    通过以上步骤,我们可以成功地将 SpringBatch 整合到 SpringBoot 应用中,创建并运行批处理作业,实现数据的批量处理和迁移。在实际项目中,你还可以根据需求配置作业调度,如使用 Quartz 进行定时触发,或者根据...

    spring-batch-reference

    3. **监控和管理**: Spring Batch提供了Actuator端点,可以监控Job的运行状态,以及使用JobExplorer和JobRepository查询Job的历史记录。 4. **错误处理和恢复**: 使用JobExecution和StepExecution的异常信息,以及...

    spring-batch-reference.rar_SpringBatch英文读物pdf_batch

    9. **作业调度(Job Scheduling)**:Spring Batch 可以与Spring Integration或Quartz等调度框架集成,实现定时或触发事件时自动运行作业。 10. **监控和管理(Monitoring and Management)**:Spring Batch 提供了...

    spring batch批处理 教程

    Spring Batch提供了监控和日志记录功能,以便开发者跟踪Job的运行情况。通过Spring Boot Actuator等工具,可以实时查看Job状态、Step进度以及异常信息。 ### 8. 总结 Spring Batch为Java开发人员提供了强大的批处理...

    Manning.Spring.Batch.in.Action.Oct.2011

    7. **错误处理和重试策略**:阐述Spring Batch的错误处理机制,包括跳过失败的项、记录错误和自动重试。 8. **分割与并行处理**:讨论如何通过Partitioner实现批处理的并行化,提高处理速度。 9. **监控与日志**:...

    springbatch_嵌入式jetty_动态控制的quartz

    支持web接口的批处理框架 ...springmvc4.0.7 springbatch3.0.7 quartz2.2.3 mysql5.6 oracle11g junit4.11 log4j1.2.17 mybatis3.4.1 druid1.0.17 smg3(决策引擎) jetty8.1.5 fastjson1.2.7 springjdbc3.2.14

    springboot-batch-master.zip_hallu91_spring_springbatch_springboo

    【标题】"springboot-batch-master.zip_hallu91_spring_springbatch_springboo" 暗示这是一个关于Spring Boot集成Spring Batch的项目示例。Spring Batch是Spring框架的一部分,专门用于处理批量处理任务,而Spring ...

    spring batch Doc

    - **批处理作业**:对于需要定期运行的任务(例如夜间运行的报告生成),Spring Batch 提供了一套完整的解决方案来支持这些需求。 - **复杂的数据转换与加载**:当涉及到多个系统的数据集成时,Spring Batch 的Item ...

    SpringBatch的简单Sample

    此外,对于失败的作业,SpringBatch 支持自动或手动重试,可以根据需要配置重试策略。 6. **持久化**: SpringBatch 使用数据库来存储作业和步骤的元数据,包括状态、执行历史、失败信息等。这使得我们可以在任何...

    Spring+Batch+Learning实例

    在这个"Spring+Batch+Learning实例"中,我们可以深入理解Spring Batch的核心概念、配置、运行机制以及如何在实际项目中应用它。 首先,Spring Batch 提供了事务管理、错误处理、日志记录等关键功能,使得开发者可以...

    Spring Batch参考文档中文版

    ### Spring Batch参考文档中文版知识点概述 #### 一、Spring Batch简介 Spring Batch是一个用于开发大批量数据处理应用的强大框架。它提供了丰富的功能集来帮助开发者构建高效、可靠的批量处理应用,尤其适用于...

Global site tag (gtag.js) - Google Analytics