http://www.4ucode.com/Study/Topic/478358

DelimitedLineTokenizer 的delimiter 默认是逗号','.names is as the fieldMap keys, it's not the header of feed file

FixedLengthTokenizer use the column index to split.

PassThroughFieldSetMapper just use the default filedSet. you can define your own field mapper.

Spring batch sample 之 text to DB
例子很简单:
txt文件如下:

   sampleSource.txt
kinaei,30
zoubin,40
ZHUTOU,65
wufeiran,51

需要存放到一张表中:

     CREATE MEMORY TABLE BATCH_TEST(NAME VARCHAR(20) NOT NULL PRIMARY KEY,AGE BIGINT)

利用sts自带的spring-batch的模板生成样板代码。自己完成的无非是reader 和 writer两块。
  下面是主要的配置代码:

  <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:batch="http://www.springframework.org/schema/batch"
xsi:schemaLocation="http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<description>Example job to get you started. It provides a
skeleton for a typical batch application.</description>
<job id="job1" xmlns="http://www.springframework.org/schema/batch">
<step id="step1" parent="simpleStep">
<tasklet>
<chunk reader="reader" writer="writer"/>
</tasklet>
</step>
</job>
<!--
<bean id="reader" class="org.springframework.sample.batch.example.ExampleItemReader">
<property name="sampleFile" value="classpath:sampleSource.txt" />
</bean>
-->
<bean id="reader" class="org.springframework.batch.item.file.FlatFileItemReader">
<property name="resource" value="classpath:sampleSource.txt" />
<property name="lineMapper" >
<bean id="defaultLineMapper" class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<property name="lineTokenizer">
<bean class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
<property name="names">
<list>
<value>name</value>
<value>age</value>
</list>
</property>
</bean>
</property>
<property name="fieldSetMapper">
<bean  class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper">
<property name="prototypeBeanName" value="testbean" />
</bean>
</property>
</bean>
</property>
</bean>
<bean id="testbean" class="org.springframework.sample.batch.example.TestBean" scope="prototype"/>
<bean id="writer" class="org.springframework.sample.batch.example.ExampleItemWriter" >
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="simpleStep"
class="org.springframework.batch.core.step.item.SimpleStepFactoryBean"
abstract="true">
<property name="transactionManager" ref="transactionManager" />
<property name="jobRepository" ref="jobRepository" />
<property name="startLimit" value="100" />
<property name="commitInterval" value="1" />
</bean>
</beans>

主要的工作就是把需要读取的文件是一个逗号分割的文件,先把每一行转换为一个bean然后交给writer去写入数据库。
首先来看一下reader,Spring提供的基础设施及其完善,几乎不用写任何代码就能把一个reader配置完成了。一个reader主要由两部分组成:
    【1】resource 告诉reader从哪里去读文件

<property name="resource" value="classpath:sampleSource.txt" />

【2】lineMapper 就是说txt文件中的每一行映射成怎样的一个bean。
      如何把文件的一行映射成为一个bean呢?
  【A】需要知道分割符号式什么,在spring 中就叫做:lineTokenizer。可能的话还要提供每个字段对应的名称。

                                        <property name="lineTokenizer">
<bean class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
<property name="names">
<list>
<value>name</value>
<value>age</value>
</list>
</property>
</bean>
</property>

这里告诉系统用逗号分隔符,并且第一字段叫name,第二个字段叫age
          【B】需要把txt文件中的字段映射到bean中的对应字段中并且做好字段的类型转换工作。Spring中就叫做fieldSetMapper

                                       <property name="fieldSetMapper">
<bean  class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper">
<property name="prototypeBeanName" value="testbean" />
</bean>
</property>

这里用到了spring的基础设施,即BeanWrapperFieldSetMapper它会根据txt文件读出的字段与给定的bean进行同名装配,自动的映射成了一个bean叫做testbean。
【C】 testbean 是什么的 定义如下

      <bean id="testbean" class="org.springframework.sample.batch.example.TestBean" scope="prototype"/>
package org.springframework.sample.batch.example;
import java.io.Serializable;
public class TestBean implements Serializable{
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}

这样reader就写好了。

剩下的就是writer了,由于spring没有提供方面的Database ItemWriters只能自己写了。

 package org.springframework.sample.batch.example;
import java.util.List;
import javax.sql.DataSource;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.item.ItemWriter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.StringUtils;
/**
* Dummy {@link ItemWriter} which only logs data it receives.
*/
public class ExampleItemWriter implements ItemWriter<Object> {
private static final Log log = LogFactory.getLog(ExampleItemWriter.class);
private DataSource dataSource;
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* @see ItemWriter#write(Object)
*/
public void write(List<? extends Object> data) throws Exception {
TestBean rs=null;
for(Object line : data){
rs=(TestBean)line;  //actual just one
}
final Object[] params=new Object[2];
params[0]=rs.getName();
params[1]=rs.getAge();
System.out.println(ToStringBuilder.reflectionToString(rs));
TransactionTemplate transactionTemplate = new TransactionTemplate(new DataSourceTransactionManager(dataSource));
transactionTemplate.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus arg0) {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.update("insert into BATCH_TEST(NAME,AGE) VALUES(?,?)",params);
return null;
}
});
}
}

配置如下:

         <bean id="writer" class="org.springframework.sample.batch.example.ExampleItemWriter" >
<property name="dataSource" ref="dataSource" />
</bean>

最后谈一下总体的感觉:
      【1】代码简单清晰许多,只需要把精力放在reader和writer的代码中。其他的如出错处理等都有spring代劳了。
【2】自动装配的这个reader用起来非常方便。
【3】自动实现了有状态的读取。为了防止读写过程中突然出错,在启动的时候重复读,或者漏读。以前读文件的时候要么是先把整个文件读写完毕后再commit,既浪费应用服务器的内存,又影响db的性能。要么要再写个文件记录读取的条数,重启后先判断读取的位置,在接着做。现在SPRING的这个reader自动提供了(当然代价是建立了记录状态的spring_batch的一系列的表),非常方便。
【4】在写writer的时候有spring来管理connection的事务提交。原来自己写的时候需要把connection传来传去以保证事务的完整性。比如如果要实现读两行再一次提交的话,可能connect 会贯穿于reader和writer或者再写个类去管理这个connection这里都提交给了spring。

实践下来我的结论是如果你要写一个读取文件,再做相应的处理后写入数据库的程序的话利用spring-batch绝对物有所值。

  • batch2.zip (36.5 KB)

spring batch相关推荐

  1. spring Batch实现数据库大数据量读写

    spring Batch实现数据库大数据量读写 博客分类: spring springBatchquartz定时调度批处理  1. data-source-context.xml Xml代码   &l ...

  2. Spring Batch在大型企业中的最佳实践

    在大型企业中,由于业务复杂.数据量大.数据格式不同.数据交互格式繁杂,并非所有的操作都能通过交互界面进行处理.而有一些操作需要定期读取大批量的数据,然后进行一系列的后续处理.这样的过程就是" ...

  3. java中batch基础_详解Spring batch 入门学习教程(附源码)

    详解Spring batch 入门学习教程(附源码) 发布时间:2020-09-08 00:28:40 来源:脚本之家 阅读:99 作者:achuo Spring batch 是一个开源的批处理框架. ...

  4. 首次使用批处理框架 Spring Batch ,被震撼到了,太强大...

    以下文章来源方志朋的博客,回复"666"获面试宝典 spring batch简介 spring batch是spring提供的一个数据处理框架.企业域中的许多应用程序需要批量处理才 ...

  5. 配置 Spring Batch 批处理失败重试

    点击上方蓝色"方志朋",选择"设为星标" 回复"666"获取独家整理的学习资料! 1. 引言 默认情况下,Spring批处理作业在执行过程中 ...

  6. Spring Batch 介绍

    在企业应用的关键环境中,通常有需要很多应用来来处理大量的应用.这商业操作包括了自动化,并且负责的处理程序来对大量数据进行高效的处理,通常这些程序不需要人工进行干预.这些事件包括有基于时间周期产生的操作 ...

  7. java批处理框架采集端_使用Spring Batch批处理框架(参考)

    本文主要介绍了春季批量框架的使用分析.文章通过实例代码详细介绍,对每个人的学习或工作都有一定的参考和学习价值,需要的朋友可以参考. 使用春季批处理作为批处理框架,可以在常规数据量不是特别大的情况下完成 ...

  8. Spring Batch事务处理

    事务模型描述 1.step之间事务独立 2.step划分成多个chunk执行,chunk事务彼此独立,互不影响:chunk开始开启一个事务,正常结束提交.chunk表示给定数量的item的操作集合,主 ...

  9. spring boot + spring batch 读数据库文件写入文本文件读文本文件写入数据库

    好久没有写博客,换了一家新公司,原来的公司用的是spring,现在这家公司用的是spring boot.然后,项目组布置了一个任务,关于两个数据库之间的表同步,我首先想到的就是spring batch ...

  10. [Spring Cloud Task]6 Spring Batch批处理应用设计原则

    2019独角兽企业重金招聘Python工程师标准>>> 概述 本文是Spring Cloud Task系列的第五篇文章,如果你尚未使用过Spring Cloud Task,请 移步s ...

最新文章

  1. HTML 5 应用程序缓存
  2. AHK 中 % 符号的用法
  3. linux下源码安装vim,ubuntu 源码编译安装最新的vim 8.0
  4. php常用操作字符串函数,php字符串几个常用的操作函数
  5. 天体运行轨迹_数字的天体运行轨迹l 周运势能量11.2512.1
  6. JMX和Spring –第2部分
  7. 拼音输入法功能大比拼
  8. 主设备号与次设备号以及申请
  9. 2021 年前端趋势预测
  10. Node.js 沙箱易受原型污染攻击
  11. 为什么 HashMap 的加载因子是0.75?我研究源码发现一个重大秘密。。。
  12. 【机器学习-公开数据集免费下载】
  13. 电子邮件服务器怎样匿名转发功能,技巧:你为什么不能匿名发送电子邮件
  14. [Unity]Unity3D游戏引擎游戏开发软件相比与其他的优势
  15. 注意:这些跳槽理由会被HR调查!
  16. 序列回帖与multi-mapped reads的处理
  17. 微信自定义菜单使用特殊字符出现的问题
  18. 磁带备份迁移到磁盘备份前的准备工作
  19. 大林算法计算机控制实验报告,实验二 大林算法实验报告
  20. Linux下随机生成密码的命令总结

热门文章

  1. 2019\Province_C_C++_B\试题A-组队
  2. Linux(三) 运行级别
  3. 【IT资讯】编程语言面临重新洗牌,这六种要凉凉
  4. 【Linux】一步一步学Linux——tail命令(42)
  5. 【Linux】一步一步学Linux——初识Linux命令解析器(10)
  6. [Qt教程] 第17篇 2D绘图(七)涂鸦板
  7. 闪灯什么意思_车灯闪1下、2下、3下各代表什么意思?关键时刻可以保命
  8. c++项目源码_C/C++学习日记:用C++制作餐饮管理系统(附源码),可以用来做毕设的项目!...
  9. 高德地图显示多个气泡_CarPlay分屏功能“硬核”上线 高德地图用户可第一时间尝鲜...
  10. 要重复多少次变成潜意识_说了多少次了!通过学校区域一定要......