spring batch + spring boot 配置

1. spring batch 批处理配置

[java]  view plain  copy
  1. import java.io.IOException;  
  2.   
  3. import org.slf4j.Logger;  
  4. import org.slf4j.LoggerFactory;  
  5. import org.springframework.batch.core.Job;  
  6. import org.springframework.batch.core.JobExecutionListener;  
  7. import org.springframework.batch.core.Step;  
  8. import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;  
  9. import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;  
  10. import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;  
  11. import org.springframework.batch.core.configuration.annotation.StepScope;  
  12. import org.springframework.batch.core.launch.support.RunIdIncrementer;  
  13. import org.springframework.batch.core.repository.JobRepository;  
  14. import org.springframework.batch.item.ItemProcessor;  
  15. import org.springframework.batch.item.ItemReader;  
  16. import org.springframework.batch.item.ItemWriter;  
  17. import org.springframework.batch.item.ParseException;  
  18. import org.springframework.batch.item.file.FlatFileItemReader;  
  19. import org.springframework.batch.item.file.LineMapper;  
  20. import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;  
  21. import org.springframework.batch.item.file.mapping.DefaultLineMapper;  
  22. import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;  
  23. import org.springframework.beans.factory.annotation.Value;  
  24. import org.springframework.context.annotation.Bean;  
  25. import org.springframework.context.annotation.Configuration;  
  26. import org.springframework.core.io.ClassPathResource;  
  27. import org.springframework.core.task.SimpleAsyncTaskExecutor;  
  28. import org.springframework.transaction.PlatformTransactionManager;  
  29.   
  30. /** 
  31.  * spring batch 配置 
  32.  * @author  
  33.  */  
  34. @Configuration  
  35. @EnableBatchProcessing  
  36. public class BlackListBatchConfiguration {  
  37.       
  38.       
  39.     private static final Logger logger = LoggerFactory.getLogger(BlackListBatchConfiguration.class);  
  40.     /** 
  41.      * 读取外部文件方法 
  42.      * @return 
  43.      * @throws IOException  
  44.      */  
  45.     @Bean  
  46.     @StepScope  
  47.     public ItemReader<BlackListDO> reader(@Value("#{jobParameters[inputFileBlack]}") String inputFile) throws IOException {   
  48.         logger.info("inputFile:"+new ClassPathResource(inputFile).getURL().getPath());  
  49.         if(inputFile == null){  
  50.             logger.error("The blacklist reader file is null");  
  51.             return null;  
  52.         }  
  53.         FlatFileItemReader<BlackListDO> reader = new FlatFileItemReader<BlackListDO>();  
  54.          
  55.         reader.setResource(new ClassPathResource(inputFile));  
  56.           
  57.         reader.setLineMapper(lineMapper());  
  58.           
  59.         reader.setLinesToSkip(1);  
  60.           
  61.         reader.open(JobCompletionNotificationListener.jobExecution.getExecutionContext());  
  62.           
  63.         return reader;  
  64.     }  
  65.       
  66.       
  67.     /** 
  68.      * 读取文本行映射POJO 
  69.      * @return 
  70.      */  
  71.     @Bean  
  72.     @StepScope  
  73.     public LineMapper<BlackListDO> lineMapper() {  
  74.         DefaultLineMapper<BlackListDO> lineMapper = new DefaultLineMapper<BlackListDO>();  
  75.         DelimitedLineTokenizer lineTokenizer = new DelimitedLineTokenizer();  
  76.         lineTokenizer.setDelimiter(",");  
  77.         lineTokenizer.setStrict(false);  
  78.         lineTokenizer.setNames(new String[] { "type","value","fraudType"});  
  79.           
  80.         BeanWrapperFieldSetMapper<BlackListDO> fieldSetMapper = new BeanWrapperFieldSetMapper<BlackListDO>();  
  81.         fieldSetMapper.setTargetType(BlackListDO.class);  
  82.         lineMapper.setLineTokenizer(lineTokenizer);  
  83.         lineMapper.setFieldSetMapper(new BlackListFieldSetMapper());  
  84.         return lineMapper;  
  85.     }  
  86.   
  87.     /** 
  88.      * 处理过程 
  89.      * @return 
  90.      */  
  91.     @Bean  
  92.     @StepScope  
  93.     public ItemProcessor<BlackListDO, BlackListDO> processor(@Value("#{jobParameters[inputFileBlack]}") String inputFile) {  
  94.         return new BlackListDOItemProcessor(inputFile);  
  95.     }  
  96.   
  97.     /** 
  98.      * 写出内容 
  99.      * @return 
  100.      */  
  101.     @Bean  
  102.     @StepScope  
  103.     public ItemWriter<BlackListDO> writer() {  
  104.         return new BlackListItemWriter();  
  105.     }  
  106.   
  107.     /** 
  108.      * 构建job 
  109.      * @param jobs 
  110.      * @param s1  
  111.      * @param listener 
  112.      * @return 
  113.      */  
  114.     @Bean  
  115.     public Job importFileJob(JobBuilderFactory jobs, Step step1,JobExecutionListener listener,JobRepository jobRepository) {  
  116.         return jobs.get("importFileJob")  
  117.                 .incrementer(new RunIdIncrementer())  
  118.                 .repository(jobRepository)  
  119.                 .listener(listener)  
  120.                 .flow(step1)  
  121.                 .end()  
  122.                 .build();  
  123.     }  
  124.       
  125.     /** 
  126.      * 声明step 
  127.      * @param stepBuilderFactory  
  128.      * @param reader  
  129.      * @param writer 
  130.      * @param processor 
  131.      * @return 
  132.      */  
  133.     @Bean  
  134.     public Step step1(StepBuilderFactory stepBuilderFactory, ItemReader<BlackListDO> reader,  
  135.             ItemWriter<BlackListDO> writer, ItemProcessor<BlackListDO, BlackListDO> processor,PlatformTransactionManager transactionManager) {  
  136.         logger.error("step1");  
  137.         return stepBuilderFactory.get("step1")  
  138.                 .<BlackListDO, BlackListDO> chunk(500)  
  139.                 .reader(reader)  
  140.                 .processor(processor)  
  141.                 .writer(writer)  
  142.                 .faultTolerant()  
  143.                 .retry(Exception.class)   // 重试  
  144.                 .noRetry(ParseException.class)  
  145.                 .retryLimit(1)           //每条记录重试一次  
  146.                 .listener(new RetryFailuireItemListener())    
  147.                 .skip(Exception.class)  
  148.                 .skipLimit(500)         //一共允许跳过200次异常  
  149.                 .taskExecutor(new SimpleAsyncTaskExecutor()) //设置并发方式执行  
  150.                 .throttleLimit(10)        //并发任务数为 10,默认为4  
  151.                 .transactionManager(transactionManager)  
  152.                 .build();  
  153.     }  
  154.       
  155. }  

  BlackListDOItemProcessor 处理类

[java]  view plain  copy
  1. import java.sql.Timestamp;  
  2. import java.util.Date;  
  3. import java.util.UUID;  
  4.   
  5. import org.springframework.batch.item.ItemProcessor;  
  6.   
  7. import com.BlackListDO;  
  8.   
  9. /** 
  10.  * @author zhengyong 
  11.  * 
  12.  */  
  13.   
  14. public class BlackListDOItemProcessor implements ItemProcessor<BlackListDO, BlackListDO> {  
  15.       
  16.     public String inputFile;  
  17.   
  18.     public BlackListDOItemProcessor() {  
  19.     }  
  20.       
  21.     public BlackListDOItemProcessor(String inputFile) {  
  22.         this.inputFile = inputFile;  
  23.     }  
  24.     // 数据处理  
  25.     public BlackListDO process(BlackListDO blackListDO) throws Exception {  
  26.         blackListDO.setDeleteFlag(0);  
  27.         blackListDO.setUuid(UUID.randomUUID().toString().replaceAll("-"""));  
  28.         return blackListDO;  
  29.     }  
  30.   
  31. }  

  BlackListItemWriter  写入数据库类

[java]  view plain  copy
  1. import org.springframework.batch.item.ItemWriter;  
  2. import org.springframework.beans.factory.annotation.Autowired;  
  3.   
  4. import com.BlackListDO;  
  5.   
  6. public class BlackListItemWriter implements ItemWriter<BlackListDO> {  
  7.   
  8.     @Override  
  9.     public void write(List<? extends BlackListDO> blackList) throws Exception {  
  10.             // 插入数据库操作   
  11.     }  
  12.       
  13. }  

  JobCompletionNotificationListener 监听任务

[java]  view plain  copy
  1. import org.springframework.batch.core.BatchStatus;  
  2. import org.springframework.batch.core.JobExecution;  
  3. import org.springframework.batch.core.listener.JobExecutionListenerSupport;  
  4. import org.springframework.beans.factory.annotation.Autowired;  
  5. import org.springframework.stereotype.Component;  
  6.   
  7. @Component  
  8. public class JobCompletionNotificationListener extends JobExecutionListenerSupport {  
  9.   
  10.     @Override  
  11.     public void afterJob(JobExecution jobExecution) {  
  12.           
  13.     }  
  14.   
  15.     @Override  
  16.     public void beforeJob(JobExecution jobExecution) {  
  17.         super.beforeJob(jobExecution);  
  18.     }  
  19. }  

  RetryFailuireItemListener 重试监听

[java]  view plain  copy
  1. import org.slf4j.Logger;  
  2. import org.slf4j.LoggerFactory;  
  3. import org.springframework.retry.RetryCallback;  
  4. import org.springframework.retry.RetryContext;  
  5. import org.springframework.retry.RetryListener;  
  6.   
  7. public class RetryFailuireItemListener implements RetryListener{  
  8.       
  9.     private static final Logger logger = LoggerFactory.getLogger(RetryFailuireItemListener.class);  
  10.   
  11.     @Override  
  12.     public <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback) {  
  13.         return true;  
  14.     }  
  15.   
  16.     @Override  
  17.     public <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback,  
  18.             Throwable throwable) {  
  19.     }  
  20.   
  21.     @Override  
  22.     public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback,  
  23.             Throwable throwable) {  
  24.         logger.error("【重试异常】:"+throwable.getMessage());  
  25.     }  
  26.   
  27. }  

2. spring boot 配置

[java]  view plain  copy
  1. import org.springframework.boot.SpringApplication;  
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;  
  3. import org.springframework.boot.builder.SpringApplicationBuilder;  
  4. import org.springframework.boot.context.web.SpringBootServletInitializer;  
  5. import org.springframework.context.annotation.ComponentScan;  
  6.   
  7. @ComponentScan("com.syncclient")  
  8. @SpringBootApplication  
  9. public class SpringBootJspApplication extends SpringBootServletInitializer{  
  10.   
  11.     /** 
  12.      * 500一批 
  13.      * oracle : 单条插入基本每分钟2.5W条(50W,19.5min) ,批量插入基本每分钟10W条(50W,4.7mim) 
  14.      * mysql  : 单条插入基本每分钟2.5W条(50W,11.4min) ,批量插入基本每分钟40W条(50W,1.3min) 
  15.      */  
  16.     @Override  
  17.     protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {  
  18.         return application.sources(SpringBootJspApplication.class);  
  19.     }  
  20.       
  21.     public static void main(String[] args) throws Exception {  
  22.         SpringApplication.run(SpringBootJspApplication.class,new String[]{"appStart=true"});  
  23.     }  
  24. }  
3. 配置文件

[java]  view plain  copy
  1. # mysql config  
  2. #spring.boot.database = mysql   
  3. #spring.datasource.url = jdbc:mysql://127.0.0.1:3306/spring_batch?useUnicode=true&characterEncoding=utf8  
  4. #spring.datasource.username = admin  
  5. #spring.datasource.password = 123456  
  6. #spring.datasource.driverClassName = com.mysql.jdbc.Driver  
  7. #spring.batch.schema = classpath:/org/springframework/batch/core/schema-mysql.sql  
  8. #spring.batch.drop = classpath:/org/springframework/batch/core/schema-drop-mysql.sql  
  9.   
  10. # oracle config  
  11. spring.boot.database = oracle   
  12. spring.datasource.url = jdbc:oracle:thin:@127.0.0.1:1521:spring_batch  
  13. spring.datasource.username = admin  
  14. spring.datasource.password = 123456  
  15. spring.datasource.driverClassName = oracle.jdbc.driver.OracleDriver  
  16. spring.batch.schema = classpath:org/springframework/batch/core/schema-oracle10g.sql  
  17. spring.batch.drop = classpath:org/springframework/batch/core/schema-drop-oracle10g.sql  
  18.   
  19. # batch config  
  20. spring.batch.job.names = importFileJob  
  21. spring.batch.job.enabled = true  
  22. spring.batch.initializer.enabled=true  

4. mybatis 配置

[java]  view plain  copy
  1. import javax.sql.DataSource;  
  2.   
  3. import org.apache.ibatis.session.SqlSessionFactory;  
  4. import org.mybatis.spring.SqlSessionFactoryBean;  
  5. import org.mybatis.spring.SqlSessionTemplate;  
  6. import org.slf4j.Logger;  
  7. import org.slf4j.LoggerFactory;  
  8. import org.springframework.beans.factory.annotation.Autowired;  
  9. import org.springframework.boot.context.properties.ConfigurationProperties;  
  10. import org.springframework.context.annotation.Bean;  
  11. import org.springframework.context.annotation.Configuration;  
  12. import org.springframework.context.annotation.Primary;  
  13. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;  
  14. import org.springframework.jdbc.datasource.DataSourceTransactionManager;  
  15. import org.springframework.transaction.PlatformTransactionManager;  
  16.   
  17. import com.alibaba.druid.pool.DruidDataSource;  
  18.   
  19. import com.BlackListDao;  
  20. import com.ProperitesUtil;  
  21.   
  22. /** 
  23.  * mybatis配置 
  24.  * 
  25.  */  
  26. @Configuration  
  27. public class MyBatisConfiguration {  
  28.   
  29.     private static final Logger logger = LoggerFactory.getLogger(MyBatisConfiguration.class);  
  30.   
  31.     @Autowired  
  32.     SqlSessionFactory sqlSessionFactory;  
  33.     @Autowired  
  34.     SqlSessionTemplate sessionTemplate;  
  35.   
  36.     @Bean  
  37.     public SqlSessionTemplate sqlSessionTemplate() {  
  38.         return new SqlSessionTemplate(sqlSessionFactory);  
  39.     }  
  40.   
  41.     @Bean  
  42.     public BlackListDao blackListMapper() {  
  43.         return sessionTemplate.getMapper(BlackListDao.class);  
  44.     }  
  45.   
  46.     @Bean  
  47.     @Primary  
  48.     @ConfigurationProperties(prefix = "spring.datasource")  
  49.     public DataSource dataSource() {  
  50.         logger.debug("初始化dataSource");  
  51.         return new DruidDataSource();  
  52.     }  
  53.   
  54.     @Bean  
  55.     public PlatformTransactionManager transactionManager(DataSource dataSource) {  
  56.         PlatformTransactionManager transactionManager = new DataSourceTransactionManager(dataSource);  
  57.         return transactionManager;  
  58.     }  
  59.   
  60.     @Bean  
  61.     public SqlSessionFactory sqlSessionFactory() throws Exception {  
  62.   
  63.         SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();  
  64.         sqlSessionFactoryBean.setDataSource(dataSource());  
  65.   
  66.         PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();  
  67.   
  68.         // 获取数据库类型  
  69.         String dataBaseType = ProperitesUtil.getPropertyValue("spring.boot.database") == null ? "mysql"  
  70.                 : ProperitesUtil.getPropertyValue("spring.boot.database");  
  71.   
  72.         String directory = "classpath:/mapper/" + dataBaseType.trim().toLowerCase() + "/*.xml";  
  73.         sqlSessionFactoryBean.setMapperLocations(resolver.getResources(directory));  
  74.   
  75.         return sqlSessionFactoryBean.getObject();  
  76.     }  
  77.   
  78. }  


5. pom.xml文件

[html]  view plain  copy
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  2.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  3.     <modelVersion>4.0.0</modelVersion>  
  4.   
  5.     <groupId>com.spring.batch</groupId>  
  6.     <artifactId>batch-test</artifactId>  
  7.     <version>0.0.1-SNAPSHOT</version>  
  8.     <packaging>jar</packaging>  
  9.   
  10.     <name>batch-test</name>  
  11.     <url>http://maven.apache.org</url>  
  12.   
  13.     <parent>  
  14.         <groupId>org.springframework.boot</groupId>  
  15.         <artifactId>spring-boot-starter-parent</artifactId>  
  16.         <version>1.2.5.RELEASE</version>  
  17.     </parent>  
  18.   
  19.     <dependencies>  
  20.         <dependency>  
  21.             <groupId>org.springframework.boot</groupId>  
  22.             <artifactId>spring-boot-starter-web</artifactId>  
  23.         </dependency>  
  24.         <dependency>  
  25.             <groupId>org.springframework.boot</groupId>  
  26.             <artifactId>spring-boot-starter-batch</artifactId>  
  27.         </dependency>  
  28.         <dependency>  
  29.             <groupId>org.springframework.batch</groupId>  
  30.             <artifactId>spring-batch-core</artifactId>  
  31.             <version>3.0.4.RELEASE</version>  
  32.         </dependency>  
  33.         <dependency>  
  34.             <groupId>org.springframework.boot</groupId>  
  35.             <artifactId>spring-boot-starter-tomcat</artifactId>  
  36.             <scope>provided</scope>  
  37.         </dependency>  
  38.         <dependency>  
  39.             <groupId>org.apache.tomcat.embed</groupId>  
  40.             <artifactId>tomcat-embed-jasper</artifactId>  
  41.             <scope>provided</scope>  
  42.         </dependency>  
  43.         <dependency>  
  44.             <groupId>javax.servlet</groupId>  
  45.             <artifactId>jstl</artifactId>  
  46.         </dependency>  
  47.         <dependency>  
  48.             <groupId>org.springframework.boot</groupId>  
  49.             <artifactId>spring-boot-starter-test</artifactId>  
  50.             <scope>test</scope>  
  51.         </dependency>       
  52.     </dependencies>  
  53.   
  54. </project>  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值