我写了以下代码:
1)在包含客户ID列表的分隔文件上循环。
2)每个客户使用-AsyncItemProcessor获得产品列表。
3)更新计数器。
物料处理器异步时如何更新计数器?
public class BulkExportItemProcessor implements ItemProcessor<String,String>
{
@Inject
public IProductRepository repository;
private StepExecution stepExecution;
@BeforeStep
public void beforeStep(StepExecution stepExecution) {
this.stepExecution = stepExecution;
}
@Override
public String process(String customerIds) {
String[] customerIdsList = customerIds.split(",");
int processRecordsIncrement = 0;
for(int i=0;i<customerIdsList.length;i++) {
String customerId = customerIdsList[i];
List<IProductDTO> products = repository.getProducts(customerId, null);
for(IProductDTO product:products) {
processRecordsIncrement++;
System.out.println("\n handling product: " + product.getProductId() + " of customer: " + customerId);
}
}
int processedRecords = stepExecution.getExecutionContext().getInt("PROCESSED_RECORDS");
processedRecords+=processRecordsIncrement;
stepExecution.getExecutionContext(). putInt("PROCESSED_RECORDS", processedRecords);
int processedCustomers = stepExecution.getExecutionContext().getInt("PROCESSED_CUST");
processedCustomers+=customerIdsList.length;
stepExecution.getExecutionContext().putInt("PROCESSED_CUST", processedCustomers);
return customerIds;
}
}
@Configuration
@EnableBatchProcessing
public class ExportBatchConfiguration
{
@Inject
public JobBuilderFactory jobBuilderFactory;
@Inject
public StepBuilderFactory stepBuilderFactory;
@Bean
public FlatFileItemReader<String> reader() {
return new FlatFileItemReaderBuilder<String>()
.name("voltItemReader")
.resource(new ClassPathResource("Customers.csv"))
.build();
}
@Bean
public Job job() {
return jobBuilderFactory.get("ProductExportJob")
.start(exportStep())
.listener()
.build();
}
@Bean
public Step exportStep() {
return stepBuilderFactory.get("ProductExportJob")
.<String, String>chunk(3)
.reader(reader())
.processor(asyncItemProcessor())
.build();
}
@Bean
public ItemProcessor<String,String> asyncItemProcessor(){
AsyncItemProcessor<String, String> asyncItemProcessor = new AsyncItemProcessor<String, String>();
asyncItemProcessor.setDelegate((ItemProcessor) new BulkExportItemProcessor());
asyncItemProcessor.setTaskExecutor(getAsyncExecutor());
return (ItemProcessor) asyncItemProcessor;
}
@Bean(name = "asyncExecutor")
public TaskExecutor getAsyncExecutor()
{
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(100);
executor.setMaxPoolSize(100);
executor.setQueueCapacity(100);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setThreadNamePrefix("AsyncExecutor-");
return executor;
}
}
答案 0 :(得分:0)
执行上下文是异步项目处理器的不同线程之间的可变共享状态。因此,您需要确保对其进行更新的部分是线程安全的。