1、概要
大多数任务都能够通过简单的单进程单线程任务处理好,但是还有一大部分现实诉求无法满足。批量任务存在两种并行模式
- 单进程、多线程
- 多进程
我们也可以细分为
- 多线程Step(单进程) Multi-thread Step
- 并行Step(单进程) Parallel Steps
- 对Step进行远程分块(多进程)Remote Chunking of Step
- 对Step进行分区 Partitioning a Step
今天我们将通过两个例子来解释多线程和并行任务...目前还仅限于单进程模式,后面会继续通过示例的方式说明多线程模式
2、开启并发并行之旅
项目依赖就不多说了,在之前的入门文章中已经说明。但是我们还需要添加如下两个依赖
1<!-- https://mvnrepository.com/artifact/com.thoughtworks.xstream/xstream --> 2<dependency> 3 <groupId>com.thoughtworks.xstream</groupId> 4 <artifactId>xstream</artifactId> 5 <version>1.4.12</version> 6</dependency> 7 8 <!-- https://mvnrepository.com/artifact/org.springframework/spring-oxm --> 9<dependency> 10 <groupId>org.springframework</groupId> 11 <artifactId>spring-oxm</artifactId> 12</dependency>
2.1 准备脚本
1create table TRANSACTION 2( 3 ACCOUNT varchar(32) null, 4 AMOUNT decimal null, 5 TIMESTAMP datetime null 6);
我们创建了一张表,用于储存文件中的数据。
2.2、准备CSV数据
15113971498870901,-546.68,2018-02-08 17:46:12 24041373995909987,-37.06,2018-02-02 21:10:33 33573694401052643,-784.93,2018-02-04 13:01:30 43543961469650122,925.44,2018-02-05 23:41:50 5....
2.3、准备XM文件
1<transactions> 2 <transaction> 3 <account>633110684460535475</account> 4 <amount>961.93</amount> 5 <timestamp>2018-02-03 18:30:51</timestamp> 6 </transaction> 7 <transaction> 8 <account>3555221131716404</account> 9 <amount>759.62</amount> 10 <timestamp>2018-02-12 20:02:01</timestamp> 11 </transaction> 12 <transaction> 13 <account>30315923571992</account> 14 <amount>648.92</amount> 15 <timestamp>2018-02-12 23:16:45</timestamp> 16 </transaction> 17 ...... 18</transactions>
2.4、多线程Step
最简单开启spring batch并发处理能力的办法就是将TaskExecutor添加到Step的配置中,如下
1@Configuration 2public class MultiThreadJobConfiguration extends BaseJobConfiguration { 3 4 public FlatFileItemReader<Transaction> fileTransactionReader() { 5 Resource resource = new FileSystemResource("csv/bigtransactions.csv"); 6 return new FlatFileItemReaderBuilder<Transaction>() 7 .saveState(false) 8 .resource(resource) 9 .delimited() 10 .names(new String[]{"account", "amount", "timestamp"}) 11 .fieldSetMapper(fieldSet -> { 12 Transaction transaction = new Transaction(); 13 transaction.setAccount(fieldSet.readString("account")); 14 transaction.setAmount(fieldSet.readBigDecimal("amount")); 15 transaction.setTimestamp(fieldSet.readDate("timestamp", "yyyy-MM-dd HH:mm:ss")); 16 return transaction; 17 }) 18 .build(); 19 } 20 21 @Bean 22 @StepScope 23 public JdbcBatchItemWriter<Transaction> writer(@Qualifier("dataSource") DataSource dataSource) { 24 return new JdbcBatchItemWriterBuilder<Transaction>() 25 .dataSource(dataSource) 26 .beanMapped() 27 .sql("INSERT INTO TRANSACTION (ACCOUNT, AMOUNT, TIMESTAMP) VALUES (:account, :amount, :timestamp)") 28 .build(); 29 } 30 31 @Bean("multithreadedJob") 32 public Job multithreadedJob() { 33 return this.jobs.get("multithreadedJob") 34 .start(step1()) 35 .build(); 36 } 37 38 @Bean 39 public Step step1() { 40 ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); 41 taskExecutor.setCorePoolSize(4); 42 taskExecutor.setMaxPoolSize(4); 43 taskExecutor.afterPropertiesSet(); 44 45 return this.steps.get("multithreadedStep") 46 .<Transaction, Transaction>chunk(1000) 47 .reader(fileTransactionReader()) 48 .writer(writer(null)) 49 .taskExecutor(taskExecutor) 50 .build(); 51 } 52}
以上代码说明,我们分了4个线程,read和writer按照每块1000条数据执行。使用我当前的Intel® Core™ i5-3210M CPU @ 2.50GHz × 4 机器读取60000万条数据并且落地花费时间1分半钟。调整chunk大小,经过测试也会发现对于性能也存在一定的影响,实际生产环境中使用需要调整优化chunk大小。
2.5、并行Step
并行的代码看起来稍微复杂一点,个人理解并行任务和多线程并发任务没有本质区别,只是区别于不同的业务场景,并行任务区别于并发任务关键在于并行任务将一个大任务拆分为多个Flow,一个Flow可以串联多个Flow,一个Flow可以包含多个Step.下面是一个例子,并行读取两个文件,一个csv文件,一个xml文件。
1@Configuration 2public class ParallelJobConfiguration extends BaseJobConfiguration { 3 4 @Bean 5 @StepScope 6 public FlatFileItemReader<Transaction> fileTransactionReader() { 7 Resource resource = new FileSystemResource("data/csv/bigtransactions.csv"); 8 return new FlatFileItemReaderBuilder<Transaction>() 9 .saveState(false) 10 .resource(resource) 11 .delimited() 12 .names(new String[]{"account", "amount", "timestamp"}) 13 .fieldSetMapper(fieldSet -> { 14 Transaction transaction = new Transaction(); 15 transaction.setAccount(fieldSet.readString("account")); 16 transaction.setAmount(fieldSet.readBigDecimal("amount")); 17 transaction.setTimestamp(fieldSet.readDate("timestamp", "yyyy-MM-dd HH:mm:ss")); 18 return transaction; 19 }) 20 .build(); 21 } 22 23 @Bean 24 @StepScope 25 public StaxEventItemReader<Transaction> xmlTransactionReader() { 26 Resource resource = new FileSystemResource("data/xml/bigtransactions.xml"); 27 Map<String, Class> map = new HashMap<>(); 28 map.put("transaction", Transaction.class); 29 map.put("account", String.class); 30 map.put("amount", BigDecimal.class); 31 map.put("timestamp", Date.class); 32 XStreamMarshaller marshaller = new XStreamMarshaller(); 33 marshaller.setAliases(map); 34 String[] formats = {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd"}; 35 marshaller.setConverters(new DateConverter("yyyy-MM-dd HH:mm:ss", formats)); 36 37 return new StaxEventItemReaderBuilder<Transaction>() 38 .name("xmlFileTransactionReader") 39 .resource(resource) 40 .addFragmentRootElements("transaction") 41 .unmarshaller(marshaller) 42 .build(); 43 } 44 45 @Bean 46 @StepScope 47 public JdbcBatchItemWriter<Transaction> jdbcBatchItemWriter(@Qualifier("dataSource") DataSource dataSource) { 48 return new JdbcBatchItemWriterBuilder<Transaction>() 49 .dataSource(dataSource) 50 .beanMapped() 51 .sql("INSERT INTO TRANSACTION (ACCOUNT, AMOUNT, TIMESTAMP) VALUES (:account, :amount, :timestamp)") 52 .build(); 53 } 54 55 56 @Bean("parallelJob") 57 public Job parallelStepsJob() { 58 59 return this.jobs.get("parallelJob") 60 .start(parallelFlow()) 61 .end() 62 .build(); 63 } 64 65 @Bean 66 public Flow parallelFlow() { 67 return new FlowBuilder<Flow>("parallelFlow") 68 .split(new SimpleAsyncTaskExecutor()) 69 .add(flow1(), flow2()) 70 .build(); 71 } 72 73 @Bean 74 public Flow flow1() { 75 return new FlowBuilder<Flow>("flow1") 76 .start(step1()) 77 .build(); 78 } 79 80 @Bean 81 public Flow flow2() { 82 return new FlowBuilder<Flow>("flow2") 83 .start(step2()) 84 .build(); 85 } 86 87 @Bean("xmlStep") 88 public Step step1() { 89 return this.steps.get("xmlStep") 90 .<Transaction, Transaction>chunk(1000) 91 .reader(xmlTransactionReader()) 92 .writer(jdbcBatchItemWriter(null)) 93 .build(); 94 } 95 96 @Bean("fileStep") 97 public Step step2() { 98 return this.steps.get("fileStep") 99 .<Transaction, Transaction>chunk(1000) 100 .reader(fileTransactionReader()) 101 .writer(jdbcBatchItemWriter(null)) 102 .build(); 103 }
2.6、运行任务
1# 执行多线程任务 2curl http://localhost:8080/launchMultiThreadjob 3 4# 执行并行任务 5curl http://localhost:8080/launchParallelJobjob 6 7# 或者通过浏览器打开上面的地址
3、参考文档
4、源码
https://github.com/cattles/fucking-great-springbatch
