Spring Batch简单入门(二)- Job配置

上一章,我们简单介绍了Spring Batch相关知识,今天我们进一步学习有关如何配置一个简单的Job。我们重新看下这张图。
Spring Batch简单入门(二)- Job配置_第1张图片

一个Job对应NStep(N>=1),一个Step包含一个Reader,一个Processor,一个Writer。我们的代码组织如下:
Spring Batch简单入门(二)- Job配置_第2张图片

  • 定义ItemReader

    @Bean
    @Qualifier("repositoryItemReader")
    public RepositoryItemReader<User> repositoryItemReader() {
        Map<String, Sort.Direction> map = new HashMap<>();
        map.put("id", Sort.Direction.DESC);
        RepositoryItemReader<User> repositoryItemReader = new RepositoryItemReader<>();
        repositoryItemReader.setRepository(userReaderRepository);
        repositoryItemReader.setPageSize(5);
        repositoryItemReader.setMethodName("findAll");
        repositoryItemReader.setSort(map);
        return repositoryItemReader;
    }

  • 定义ItemProcessor

    @Override
    public People process(User user) throws Exception {
        final String firstName = user.getFirstName().toUpperCase();
        final String lastName = user.getLastName().toUpperCase();
        final People transformedPeople = People.builder()
                .firstName(firstName)
                .lastName(lastName)
                .personId(UUID.randomUUID().toString())
                .build();
        log.info("converting (" + user + ") into (" + transformedPeople + ")");
        return transformedPeople;
    }
  • 定义ItemWriter

    @Bean
    @Qualifier("repositoryItemWriter")
    public RepositoryItemWriter repositoryItemWriter() {
        RepositoryItemWriter peopleRepositoryItemWriter = new RepositoryItemWriter<>();
        peopleRepositoryItemWriter.setRepository(peopleCrudRepository);
        peopleRepositoryItemWriter.setMethodName("save");
        return peopleRepositoryItemWriter;
    }
  • 定义Step如下:

    @Bean
    public Step stepWithRepository() {
        return stepBuilderFactory.get("stepWithRepository")
                .chunk(10)
                .reader(repositoryItemReader)
                .processor(userPeopleItemProcessor)
                .writer(repositoryItemWriter)
                .build();
    }
  • 定义Job
@Configuration
public class RepositoryJob {
    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private Step stepWithRepositoryReaderAndWriter;

    @Autowired
    private Step stepWithRepository;

    @Bean
    public Job jobWithRepositoryStep(@Autowired CommonJobListener commonJobListener) {
        return jobBuilderFactory.get("jobWithRepositoryStep")
                .incrementer(new RunIdIncrementer())
                .listener(commonJobListener)
                .flow(stepWithRepository)
                .end()
                .build();
    }
}
  • 暴露Rest接口,以JobLauncher启动指定Job

    @Autowired
    private JobLaunchService jobLaunchService;

    @Autowired
    private Job jobWithRepositoryStep;

    @GetMapping
    public JobResult launchJobWithRepositoryStep() {
        return jobLaunchService.launchJob(jobWithRepositoryStep);
    }

  • 其中JobLaunchService定义如下:
@Service
@Slf4j
public class JobLaunchService {
    @Autowired
    private JobLauncher jobLauncher;

    public JobResult launchJob(Job job) {
        try {
            JobParameters jobParameters = new JobParametersBuilder()
                    .addDate("timestamp", Calendar.getInstance().getTime())
                    .toJobParameters();
            JobExecution jobExecution = jobLauncher.run(job, jobParameters);
            return JobResult.builder()
                    .jobName(job.getName())
                    .jobId(jobExecution.getJobId())
                    .jobExitStatus(jobExecution.getExitStatus())
                    .timestamp(Calendar.getInstance().getTimeInMillis())
                    .build();
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException("launch job exception ", e);
        }
    }
}

这样,一个完整的Job就配置完成了,你可以通过简单的HTTP接口调用启动指定Job。更多源码请参考:https://github.com/ypmc/spring-cloud/tree/master/spring-batch

你可能感兴趣的:(Java,架构,Spring,中间件)