如何使用Spring Batch进行批处理任务管理

  import org.springframework.batch.item.ItemProcessor;

  import org.springframework.batch.item.ItemReader;

  import org.springframework.batch.item.ItemWriter;

  import org.springframework.context.annotation.Bean;

  import org.springframework.jdbc.core.JdbcTemplate;

  import org.springframework.jdbc.datasource.DriverManagerDataSource;

  import javax.sql.DataSource;

  import java.util.List;

  @Configuration

  public class BatchConfiguration {

  @Bean

  public DataSource dataSource() {

  DriverManagerDataSource dataSource = new DriverManagerDataSource();

  dataSource.setDriverClassName("org.hsqldb.jdbc.JDBCDriver");

  dataSource.setUrl("jdbc:hsqldb:mem:testdb");

  dataSource.setUsername("sa");

  dataSource.setPassword("");

  return dataSource;

  }

  @Bean

  public JdbcTemplate jdbcTemplate(DataSource dataSource) {

  return new JdbcTemplate(dataSource);

  }

  @Bean

  public ItemReader reader(JdbcTemplate jdbcTemplate) {

  return () -> {

  List data = jdbcTemplate.queryForList("SELECT name FROM people", String.class);

  return data.iterator().hasNext() ? data.iterator().next() : null;

  };

  }

  @Bean

  public ItemProcessor processor() {

  return item -> item.toUpperCase();

  }

  @Bean

  public ItemWriter writer(JdbcTemplate jdbcTemplate) {

  return items -> {

  for (String item : items) {

  jdbcTemplate.update("INSERT INTO processed_people (name) VALUES (?)", item);

  }

  };

  }

  @Bean

  public Job job(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory) {

  Step step = stepBuilderFactory.get("step1")

  .chunk(5)

  .reader(reader(null))

  .processor(processor())

  .writer(writer(null))

  .build();

  return jobBuilderFactory.get("job")

  .incrementer(new RunIdIncrementer())

  .start(step)

  .build();

  }

  }