使用Spring Batch批处理框架(参考)

  本文主要介绍了春季批量框架的使用分析。文章通过实例代码详细介绍,对每个人的学习或工作都有一定的参考和学习价值,需要的朋友可以参考。

  使用春季批处理作为批处理框架,可以在常规数据量不是特别大的情况下完成离线计算。

  现在写一个简单的入门级例子。http://m.jlnk3659999.com

  这里的默认设置是每个人都已经掌握了Spring Batch的基本知识,这个例子只是为了快速实现手。

  目标1:程序随机生成字符串,在春季批处理后,在字符串后统一添加“-processed”,并输出它们

  目标2:程序读取txt文件,在春季批处理之后,统一添加上述字段并输出它们。

  春季分批过程

  读取数据-项目读取器处理数据-项目处理数据写入-项目写入

  根据对目标的分析,两个目标的输入数据源不同,处理方法基本相同,数据完成后的写入规则相同。

  由此可以分段完成代码http://mip.0834jl.com

  itemReader

  目标一

  这里没有使用Spring Batch自带的集中reader,所以自定义了随机生成字符串的reader

  这里代码并不完善,reader会无线循环生成随机字符串,但不影响本次学习的目的

public class MyItemReader implements ItemReader<String> {
@Override
public String read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
return RandomStringUtils.randomAlphabetic(10);
}
}

  目标二

  由于是读取文件中的内容,所以不用自定义reader实现,可直接使用FlatFileItemReader,在Batch的config中配置即可

@Bean
public ItemReader<String> textReader(){

FlatFileItemReader<String> reader=new FlatFileItemReader<>();
File file = new File("D:\\FTP\\ttest.txt");
reader.setResource(new FileSystemResource(file));
reader.setLineMapper(new LineMapper<String>() {
@Overridehttp://www.jl0834.com
public String mapLine(String line, int lineNumber) throws Exception {
return line;
}
});
return reader;

}

  itemProcess

  这里采用同一种处理方式即可

public class MyItemProcessor implements ItemProcessor<String,String> {

@Override
public String process(String s) throws Exception {
return s+"---------PROCESSED";
}
}

猜你喜欢

转载自www.cnblogs.com/HanaKana/p/12106457.html