Spring Batch如何在写入步骤之前处理数据列表

时间:2014-10-11 10:56:34

标签: java spring batch-processing spring-batch

我正在尝试从数据库中读取客户端数据并将处理后的数据写入平面文件。 但是我需要在写入数据之前处理ItemReader的整个结果。

例如,我正在从数据库行读取Client:

public class Client {
    private String id;
    private String subscriptionCode;
    private Boolean activated;
}

但是我想要计算和编写按subscriptionCode分组激活的用户数量:

public class Subscription {
    private String subscriptionCode;
    private Integer activatedUserCount;
}

我不知道如何使用ItemReader / ItemProcessor / ItemWriter执行此操作,您能帮帮我吗?

BatchConfiguration:

@CommonsLog
@Configuration
@EnableBatchProcessing
@EnableAutoConfiguration
public class BatchConfiguration {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Bean
    public Step step1() {
        return stepBuilderFactory.get("step1")
                .<Client, Client> chunk(1000)
                .reader(new ListItemReader<Client>(new ArrayList<Client>() { // Just for test
                    {
                        add(Client.builder().id("1").subscriptionCode("AA").activated(true).build());
                        add(Client.builder().id("2").subscriptionCode("BB").activated(true).build());
                        add(Client.builder().id("3").subscriptionCode("AA").activated(false).build());
                        add(Client.builder().id("4").subscriptionCode("AA").activated(true).build());
                    }
                }))
                .processor(new ItemProcessor<Client, Client>() {
                    public Client process(Client item) throws Exception {
                        log.info(item);
                        return item;
                    }
                })
                .writer(new ItemWriter<Client>() {
                    public void write(List<? extends Client> items) throws Exception {
                        // Only here I can use List of Client
                        // How can I process this list before to fill Subscription objects ?
                    }
                })
                .build();
    }

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

主要应用:

public class App {
    public static void main(String[] args) throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException {
        System.exit(SpringApplication.exit(SpringApplication.run(BatchConfiguration.class, args)));
    }
}

2 个答案:

答案 0 :(得分:1)

如果我从您的评论中了解到您需要对激活的帐户进行总结,对吧? 您可以为正在处理的每个Subscription创建一个Client,并使用ItemWriterLister.afterWrite将上面创建的Subscription项写入数据库。

答案 1 :(得分:0)

我找到了基于ItemProcessor的解决方案:

@Bean
public Step step1() {
  return stepBuilderFactory.get("step1")
      .<Client, Subscription> chunk(1000)
      .reader(new ListItemReader<Client>(new ArrayList<Client>() {
        {
          add(Client.builder().id("1").subscriptionCode("AA").activated(true).build());
          add(Client.builder().id("2").subscriptionCode("BB").activated(true).build());
          add(Client.builder().id("3").subscriptionCode("AA").activated(false).build());
          add(Client.builder().id("4").subscriptionCode("AA").activated(true).build());
        }
      }))
      .processor(new ItemProcessor<Client, Subscription>() {
        private List<Subscription> subscriptions;

        public Subscription process(Client item) throws Exception {
          for (Subscription s : subscriptions) { // try to retrieve existing element
            if (s.getSubscriptionCode().equals(item.getSubscriptionCode())) { // element found
              if(item.getActivated()) {
                s.getActivatedUserCount().incrementAndGet(); // increment user count
                log.info("Incremented subscription : " + s);
              }                             
              return null; // existing element -> skip
            }
          }
          // Create new Subscription
          Subscription subscription = Subscription.builder().subscriptionCode(item.getSubscriptionCode()).activatedUserCount(new AtomicInteger(1)).build();
          subscriptions.add(subscription);
          log.info("New subscription : " + subscription);
          return subscription;
        }

        @BeforeStep
        public void initList() {
          subscriptions = Collections.synchronizedList(new ArrayList<Subscription>());
        }

        @AfterStep
        public void clearList() {
          subscriptions.clear();
        }
      })
      .writer(new ItemWriter<Subscription>() {                  
        public void write(List<? extends Subscription> items) throws Exception {
          log.info(items);
          // do write stuff
        }                   
      })
      .build();
}

但我必须在Subscription中保留第二个ItemProcessor列表(我不知道线程安全且有效吗?)。您对此解决方案有何看法?